diff --git a/python/py313/Lib/site-packages/Cryptodome/__init__.py b/python/py313/Lib/site-packages/Cryptodome/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..398df277d8427eee505b0d638718705385c0aa69 --- /dev/null +++ b/python/py313/Lib/site-packages/Cryptodome/__init__.py @@ -0,0 +1,6 @@ +__all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util', 'Signature', + 'IO', 'Math'] + +version_info = (3, 23, '0') + +__version__ = ".".join([str(x) for x in version_info]) diff --git a/python/py313/Lib/site-packages/Cryptodome/__init__.pyi b/python/py313/Lib/site-packages/Cryptodome/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2e60585c7ea97212da2e79dedc5a8d4459101e04 --- /dev/null +++ b/python/py313/Lib/site-packages/Cryptodome/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Tuple, Union + +version_info : Tuple[int, int, Union[int, str]] +__version__ : str diff --git a/python/py313/Lib/site-packages/Cryptodome/py.typed b/python/py313/Lib/site-packages/Cryptodome/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/py313/Lib/site-packages/README.rst b/python/py313/Lib/site-packages/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..741f2ad9687e6a6c2d52423a775538baec445177 --- /dev/null +++ b/python/py313/Lib/site-packages/README.rst @@ -0,0 +1 @@ +This is a dummy package designed to prevent namesquatting on PyPI. You should install `beautifulsoup4 `_ instead. diff --git a/python/py313/Lib/site-packages/__pycache__/brotli.cpython-313.pyc b/python/py313/Lib/site-packages/__pycache__/brotli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59604b34b371b54c4ba259cf5487379a168122f1 Binary files /dev/null and b/python/py313/Lib/site-packages/__pycache__/brotli.cpython-313.pyc differ diff --git a/python/py313/Lib/site-packages/__pycache__/patch_ng.cpython-313.pyc b/python/py313/Lib/site-packages/__pycache__/patch_ng.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1571ef9d7a568ba82c7d3c05adf1033415506eb9 Binary files /dev/null and b/python/py313/Lib/site-packages/__pycache__/patch_ng.cpython-313.pyc differ diff --git a/python/py313/Lib/site-packages/__pycache__/texttable.cpython-313.pyc b/python/py313/Lib/site-packages/__pycache__/texttable.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c849cf06f613c242531909de4b60639003d2c0c Binary files /dev/null and b/python/py313/Lib/site-packages/__pycache__/texttable.cpython-313.pyc differ diff --git a/python/py313/Lib/site-packages/aqt/__init__.py b/python/py313/Lib/site-packages/aqt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4b0c66da9c1b8c5390e84d8ec7c80d83d1e859 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/__init__.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# +# Copyright (C) 2018 Linus Jahn +# Copyright (C) 2019-2021 Hiroshi Miura +# +# 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. + +import sys +from multiprocessing import freeze_support + +if sys.version_info.major == 2: + print("aqtinstall requires python 3!") + sys.exit(1) + +from aqt.installer import Cli +from aqt.version import __version__ + +__all__ = ["__version__"] + + +def main(): + # For Windows standalone binaries, this is a noop on all other environments. + freeze_support() + cli = Cli() + return cli.run() diff --git a/python/py313/Lib/site-packages/aqt/__main__.py b/python/py313/Lib/site-packages/aqt/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..c025df4f7742b0d78831998086ebd01053e4f730 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/__main__.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# +# Copyright (C) 2019-2021 Hiroshi Miura +# +# 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. + +import sys + +from . import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python/py313/Lib/site-packages/aqt/archives.py b/python/py313/Lib/site-packages/aqt/archives.py new file mode 100644 index 0000000000000000000000000000000000000000..26fce63d8d069cad3e6e3dc7974c80eff6a02bc2 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/archives.py @@ -0,0 +1,716 @@ +#!/usr/bin/env python +# +# Copyright (C) 2018 Linus Jahn +# Copyright (C) 2019-2022 Hiroshi Miura +# +# 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. +import posixpath +from dataclasses import dataclass, field +from itertools import islice, zip_longest +from logging import getLogger +from typing import Any, Dict, Iterable, List, Optional, Set, Tuple +from xml.etree.ElementTree import Element # noqa + +from defusedxml import ElementTree + +from aqt.exceptions import ArchiveDownloadError, ArchiveListError, ChecksumDownloadFailure, NoPackageFound +from aqt.helper import Settings, get_hash, getUrl, ssplit +from aqt.metadata import QtRepoProperty, Version + + +@dataclass +class UpdateXmls: + target_folder: str + xml_text: str + + +@dataclass +class TargetConfig: + version: str + target: str + arch: str + os_name: str + + +@dataclass +class QtPackage: + name: str + base_url: str + archive_path: str + archive: str + archive_install_path: str + package_desc: str + pkg_update_name: str + version: Optional[Version] = field(default=None) + + def __repr__(self): + v_info = f", version={self.version}" if self.version else "" + return f"QtPackage(name={self.name}, archive={self.archive}{v_info})" + + def __str__(self): + v_info = f", version={self.version}" if self.version else "" + return ( + f"QtPackage(name={self.name}, url={self.archive_path}, " + f"archive={self.archive}, desc={self.package_desc}" + f"{v_info})" + ) + + +class ModuleToPackage: + """ + Holds a mapping of module names to a list of Updates.xml PackageUpdate names. + For example, we could have the following: + {"qtcharts": ["qt.qt6.620.addons.qtcharts.arch", qt.qt6.620.qtcharts.arch", qt.620.addons.qtcharts.arch",]) + It also contains a reverse mapping of PackageUpdate names to module names, so that + lookup of a package name and removal of a module name can be done in constant time. + Without this reverse mapping, QtArchives._parse_update_xml would run at least one + linear search on the forward mapping for each module installed. + + The list of PackageUpdate names consists of all the possible names for the PackageUpdate. + The naming conventions for each PackageUpdate are not predictable, so we need to maintain + a list of possibilities. While reading Updates.xml, if we encounter any one of the package + names on this list, we can use it to install the package "qtcharts". + + Once we have installed the package, we need to remove the package "qtcharts" from this + mapping, so we can keep track of what still needs to be installed. + """ + + def __init__(self, initial_map: Dict[str, List[str]]): + self._modules_to_packages: Dict[str, List[str]] = initial_map + self._packages_to_modules: Dict[str, str] = { + value: key for key, list_of_values in initial_map.items() for value in list_of_values + } + + def add(self, module_name: str, package_names: List[str]): + self._modules_to_packages[module_name] = self._modules_to_packages.get(module_name, []) + package_names + for package_name in package_names: + assert package_name not in self._packages_to_modules, "Detected a package name collision" + self._packages_to_modules[package_name] = module_name + + def remove_module_for_package(self, package_name: str): + module_name = self._packages_to_modules[package_name] + for package_name in self._modules_to_packages[module_name]: + self._packages_to_modules.pop(package_name) + self._modules_to_packages.pop(module_name) + + def has_package(self, package_name: str): + return package_name in self._packages_to_modules + + def get_modules(self) -> Iterable[str]: + return self._modules_to_packages.keys() + + def __len__(self) -> int: + return len(self._modules_to_packages) + + def __format__(self, format_spec) -> str: + return str(sorted(set(self._modules_to_packages.keys()))) + + +@dataclass +class PackageUpdate: + """ + Data class to hold package data. + key is its name. + """ + + name: str + display_name: str + description: str + release_date: str + full_version: str + dependencies: Iterable[str] + auto_dependon: Iterable[str] + downloadable_archives: Iterable[str] + archive_install_paths: Iterable[str] + default: bool + virtual: bool + base: str + + def __post_init__(self): + for iter_of_str in self.dependencies, self.auto_dependon, self.downloadable_archives, self.archive_install_paths: + assert isinstance(iter_of_str, Iterable) and not isinstance(iter_of_str, str) + for _str in self.name, self.display_name, self.description, self.release_date, self.full_version, self.base: + assert isinstance(_str, str) + for boolean in self.default, self.virtual: + assert isinstance(boolean, bool) + + @property + def version(self): + return Version.permissive(self.full_version) + + @property + def arch(self): + return self.name.split(".")[-1] + + def is_base_package(self) -> bool: + return self.name in ( + f"qt.qt{self.version.major}.{self._version_str()}.{self.arch}", + f"qt.{self._version_str()}.{self.arch}", + ) + + def _version_str(self) -> str: + return ("{0.major}{0.minor}" if self.version == Version("5.9.0") else "{0.major}{0.minor}{0.patch}").format( + self.version + ) + + +@dataclass(init=False) +class Updates: + package_updates: List[PackageUpdate] + + def __init__(self) -> None: + self.package_updates = [] + + def extend(self, other): + self.package_updates.extend(other.package_updates) + + @staticmethod + def fromstring(base, update_xml_text: str): + try: + update_xml = ElementTree.fromstring(update_xml_text) + except ElementTree.ParseError as perror: + raise ArchiveListError(f"Downloaded metadata is corrupted. {perror}") from perror + updates = Updates() + extract_xpath = "Operations/Operation[@name='Extract']/Argument" + for packageupdate in update_xml.iter("PackageUpdate"): + pkg_name = updates._get_text(packageupdate.find("Name")) + display_name = updates._get_text(packageupdate.find("DisplayName")) + full_version = updates._get_text(packageupdate.find("Version")) + package_desc = updates._get_text(packageupdate.find("Description")) + release_date = updates._get_text(packageupdate.find("ReleaseDate")) + dependencies = updates._get_list(packageupdate.find("Dependencies")) + auto_dependon = updates._get_list(packageupdate.find("AutoDependOn")) + archives = updates._get_list(packageupdate.find("DownloadableArchives")) + archive_install_paths = updates._get_list(None) + default = updates._get_boolean(packageupdate.find("Default")) + virtual = updates._get_boolean(packageupdate.find("Virtual")) + if packageupdate.find(extract_xpath) is not None: + arc_args = map( + lambda x: x.text, + islice(packageupdate.iterfind(extract_xpath), 1, None, 2), + ) + archives = ssplit(", ".join(arc_args)) + path_args = map( + lambda x: x.text.replace("@TargetDir@/", "", 1), + islice(packageupdate.iterfind(extract_xpath), 0, None, 2), + ) + archive_install_paths = ssplit(", ".join(path_args)) + updates.package_updates.append( + PackageUpdate( + pkg_name, + display_name, + package_desc, + release_date, + full_version, + dependencies, + auto_dependon, + archives, + archive_install_paths, + default, + virtual, + base, + ) + ) + return updates + + def get(self, target: Optional[str] = None): + if target is None: + return self.package_updates + for update in self.package_updates: + if update.name == target: + return update + return None + + def get_from(self, arch: str, is_include_base: bool, target_packages: Optional[ModuleToPackage] = None): + result = [] + for update in self.package_updates: + # If we asked for `--noarchives`, we don't want the base module + if not is_include_base and update.is_base_package(): + continue + if target_packages is not None and not target_packages.has_package(update.name): + continue + if arch in update.name: + result.append(update) + return result + + def merge(self, other): + self.package_updates.extend(other.package_updates) + + def get_depends(self, target: str) -> Iterable[str]: + # initialize + filo = [target] + packages = [] + visited = [] + # dfs look-up + while len(filo) > 0: + next = filo.pop() + packages.append(next) + for entry in self.package_updates: + if entry.name == next: + visited.append(next) + if entry.dependencies is not None: + for depend in entry.dependencies: + if depend not in visited: + filo.append(depend) + return packages + + def _get_text(self, item: Optional[Element]) -> str: + if item is not None and item.text is not None: + return item.text + return "" + + def _get_list(self, item: Optional[Element]) -> Iterable[str]: + if item is not None and item.text is not None: + return ssplit(item.text) + else: + return [] + + def _get_boolean(self, item) -> bool: + return bool("true" == item) + + +class QtArchives: + """Download and hold Qt archive packages list. + It access to download.qt.io site and get Update.xml file. + It parse XML file and store metadata into list of QtPackage object. + """ + + def __init__( + self, + os_name: str, + target: str, + version_str: str, + arch: str, + base: str, + subarchives: Optional[Iterable[str]] = None, + modules: Optional[Iterable[str]] = None, + all_extra: bool = False, + is_include_base_package: bool = True, + timeout=(5, 5), + ): + self.version: Version = Version(version_str) + self.target: str = target + self.arch: str = arch + self.os_name: str = os_name + self.all_extra: bool = all_extra + self.base: str = base + self.logger = getLogger("aqt.archives") + self.archives: List[QtPackage] = [] + self.subarchives: Optional[Iterable[str]] = subarchives + self.mod_list: Set[str] = set(modules or []) + self.is_include_base_package: bool = is_include_base_package + self.timeout = timeout + try: + self._get_archives() + except ArchiveDownloadError as e: + self.handle_missing_updates_xml(e) + + def handle_missing_updates_xml(self, e: ArchiveDownloadError): + msg = f"Failed to locate XML data for Qt version '{self.version}'." + help_msg = f"Please use 'aqt list-qt {self.os_name} {self.target}' to show versions available." + raise ArchiveListError(msg, suggested_action=[help_msg]) from e + + def should_filter_archives(self, package_name: str) -> bool: + """ + This tells us, based on the PackageUpdate.Name property, whether or not the `self.subarchives` + list should be used to filter out archives that we are not interested in. + + If `package_name` is a base module or a debug_info module, the `subarchives` list will apply to it. + """ + return package_name in self._base_package_names() or "debug_info" in package_name + + def _version_str(self) -> str: + return ("{0.major}{0.minor}" if self.version == Version("5.9.0") else "{0.major}{0.minor}{0.patch}").format( + self.version + ) + + def _arch_ext(self) -> str: + ext = QtRepoProperty.extension_for_arch(self.arch, self.version >= Version("6.0.0")) + return ("_" + ext) if ext else "" + + def _base_module_name(self) -> str: + """ + This is the name for the base Qt module, whose PackageUpdate.Name property would be + 'qt.123.gcc_64' or 'qt.qt1.123.gcc_64' for Qt 1.2.3, for architecture gcc_64. + """ + return "qt_base" + + def _base_package_names(self) -> Iterable[str]: + """ + This is a list of all potential PackageUpdate.Name properties for the base Qt module, + which would be 'qt.123.gcc_64' or 'qt.qt1.123.gcc_64' for Qt 1.2.3, for architecture gcc_64, + or 'qt.123.src' or 'qt.qt1.123.src' for the source module. + """ + return ( + f"qt.qt{self.version.major}.{self._version_str()}.{self.arch}", + f"qt.{self._version_str()}.{self.arch}", + ) + + def _module_name_suffix(self, module: str) -> str: + return f"{module}.{self.arch}" + + def _target_packages(self) -> ModuleToPackage: + """Build mapping between module names and their possible package names""" + if self.all_extra: + return ModuleToPackage({}) + + base_package = {self._base_module_name(): list(self._base_package_names())} + target_packages = ModuleToPackage(base_package if self.is_include_base_package else {}) + + for module in self.mod_list: + suffix = self._module_name_suffix(module) + prefix = "qt.qt{}.{}.".format(self.version.major, self._version_str()) + basic_prefix = "qt.{}.".format(self._version_str()) + + # All possible package name formats + package_names = [ + f"{prefix}{suffix}", + f"{basic_prefix}{suffix}", + f"{prefix}addons.{suffix}", + f"{basic_prefix}addons.{suffix}", + f"extensions.{module}.{self._version_str()}.{self.arch}", + f"{prefix}{module}.{self.arch}", # Qt6.8+ format + f"{basic_prefix}{module}.{self.arch}", # Qt6.8+ format + f"{prefix}addons.{module}.{self.arch}", # Qt6.8+ addons format + f"{basic_prefix}addons.{module}.{self.arch}", # Qt6.8+ addons format + ] + + target_packages.add(module, list(set(package_names))) # Remove duplicates + + return target_packages + + def _get_archives(self): + if self.version >= Version("6.8.0"): + name = ( + f"qt{self.version.major}_{self._version_str()}" + f"/qt{self.version.major}_{self._version_str()}{self._arch_ext()}" + ) + else: + name = f"qt{self.version.major}_{self._version_str()}{self._arch_ext()}" + self._get_archives_base(name, self._target_packages()) + + def _get_archives_base(self, name, target_packages): + os_name = self.os_name + if self.target == "android" and self.version >= Version("6.7.0"): + os_name = "all_os" + elif self.os_name == "windows": + os_name += "_x86" + elif os_name != "linux_arm64" and os_name != "all_os" and os_name != "windows_arm64": + os_name += "_x64" + os_target_folder = posixpath.join( + "online/qtsdkrepository", + os_name, + self.target, + # tools_ifw/ + name, + ) + update_xml_url = posixpath.join(os_target_folder, "Updates.xml") + update_xml_text = self._download_update_xml(update_xml_url) + update_xmls = [UpdateXmls(os_target_folder, update_xml_text)] + + if self.version >= Version("6.8.0"): + arch = self.arch + if self.os_name == "windows": + arch = self.arch.replace("win64_", "", 1) + elif self.os_name == "linux": + arch = "x86_64" + elif self.os_name == "linux_arm64": + arch = "arm64" + for ext in ["qtwebengine", "qtpdf"]: + extensions_target_folder = posixpath.join( + "online/qtsdkrepository", os_name, "extensions", ext, self._version_str(), arch + ) + extensions_xml_url = posixpath.join(extensions_target_folder, "Updates.xml") + # The extension may or may not exist for this version and arch. + try: + extensions_xml_text = self._download_update_xml(extensions_xml_url, True) + except ArchiveDownloadError: + # In case _download_update_xml failed to get the url because of no extension. + pass + else: + if extensions_xml_text: + self.logger.info("Found extension {}".format(ext)) + update_xmls.append(UpdateXmls(extensions_target_folder, extensions_xml_text)) + + self._parse_update_xmls(update_xmls, target_packages) + + def _download_update_xml(self, update_xml_path: str, silent: bool = False) -> Optional[str]: + """Hook for unit test.""" + if not Settings.ignore_hash: + try: + xml_hash: Optional[bytes] = get_hash(update_xml_path, Settings.hash_algorithm, self.timeout) + except ChecksumDownloadFailure: + if silent: + return None + else: + self.logger.warning( + "Failed to download checksum for the file '{}'. This may happen on unofficial mirrors.".format( + update_xml_path + ) + ) + xml_hash = None + else: + xml_hash = None + return getUrl(posixpath.join(self.base, update_xml_path), self.timeout, xml_hash) + + def _parse_update_xml( + self, os_target_folder: str, update_xml_text: str, target_packages: Optional[ModuleToPackage] + ) -> None: + if not target_packages: + target_packages = ModuleToPackage({}) + update_xml = Updates.fromstring(self.base, update_xml_text) + base_url = self.base + if self.all_extra: + package_updates = update_xml.get_from(self.arch, self.is_include_base_package) + else: + package_updates = update_xml.get_from(self.arch, self.is_include_base_package, target_packages) + for packageupdate in package_updates: + if not self.all_extra: + target_packages.remove_module_for_package(packageupdate.name) + should_filter_archives: bool = bool(self.subarchives) and self.should_filter_archives(packageupdate.name) + + for archive, archive_install_path in zip_longest( + packageupdate.downloadable_archives, packageupdate.archive_install_paths, fillvalue="" + ): + archive_name = archive.split("-", maxsplit=1)[0] + if should_filter_archives and self.subarchives is not None and archive_name not in self.subarchives: + continue + archive_path = posixpath.join( + # online/qtsdkrepository/linux_x64/desktop/qt5_5150/ + os_target_folder, + # qt.qt5.5150.gcc_64/ + packageupdate.name, + # 5.15.0-0-202005140804qtbase-Linux-RHEL_7_6-GCC-Linux-RHEL_7_6-X86_64.7z + packageupdate.full_version + archive, + ) + self.archives.append( + QtPackage( + name=archive_name, + base_url=base_url, + archive_path=archive_path, + archive=archive, + archive_install_path=archive_install_path, + package_desc=packageupdate.description, + pkg_update_name=packageupdate.name, # For testing purposes + ) + ) + + def _parse_update_xmls(self, update_xmls: list[UpdateXmls], target_packages: Optional[ModuleToPackage]) -> None: + if not target_packages: + target_packages = ModuleToPackage({}) + for update_xml in update_xmls: + self._parse_update_xml(update_xml.target_folder, update_xml.xml_text, target_packages) + # if we have located every requested package, then target_packages will be empty + if not self.all_extra and len(target_packages) > 0: + message = f"The packages {target_packages} were not found while parsing XML of package information!" + raise NoPackageFound(message, suggested_action=self.help_msg(list(target_packages.get_modules()))) + + def _append_tool_update(self, os_target_folder, update_xml, target, tool_version_str): + packageupdate = update_xml.get(target) + if packageupdate is None: + message = f"The package '{self.arch}' was not found while parsing XML of package information!" + raise NoPackageFound(message, suggested_action=self.help_msg()) + name = packageupdate.name + named_version = packageupdate.full_version + if tool_version_str and named_version != tool_version_str: + message = f"The package '{self.arch}' has the version '{named_version}', not the requested '{self.version}'." + raise NoPackageFound(message, suggested_action=self.help_msg()) + package_desc = packageupdate.description + downloadable_archives = packageupdate.downloadable_archives + archive_install_paths = packageupdate.archive_install_paths + if not downloadable_archives: + message = f"The package '{self.arch}' contains no downloadable archives!" + raise NoPackageFound(message) + for archive, archive_install_path in zip_longest(downloadable_archives, archive_install_paths, fillvalue=""): + archive_path = posixpath.join( + # online/qtsdkrepository/linux_x64/desktop/tools_ifw/ + os_target_folder, + # qt.tools.ifw.41/ + name, + # 4.1.1-202105261130ifw-linux-x64.7z + f"{named_version}{archive}", + ) + self.archives.append( + QtPackage( + name=name, + base_url=self.base, + archive_path=archive_path, + archive=archive, + archive_install_path=archive_install_path, + package_desc=package_desc, + pkg_update_name=name, # Redundant + ) + ) + + def help_msg(self, missing_modules: Optional[List[str]] = None) -> List[str]: + _missing_modules: List[str] = missing_modules or [] + base_cmd = f"aqt list-qt {self.os_name} {self.target}" + arch = f"Please use '{base_cmd} --arch {self.version}' to show architectures available." + mods = f"Please use '{base_cmd} --modules {self.version} ' to show modules available." + has_base_pkg: bool = self._base_module_name() in _missing_modules + has_non_base_pkg: bool = len(list(_missing_modules)) > 1 or not has_base_pkg + messages = [] + if has_base_pkg: + messages.append(arch) + if has_non_base_pkg: + messages.append(mods) + return messages + + def get_packages(self) -> List[QtPackage]: + """ + It returns an archive package list. + + :return package list + :rtype: List[QtPackage] + """ + return self.archives + + def get_target_config(self) -> TargetConfig: + """Get target configuration + + :return: configured target and its version with arch + :rtype: TargetConfig object + """ + return TargetConfig(str(self.version), self.target, self.arch, self.os_name) + + +class SrcDocExamplesArchives(QtArchives): + """Hold doc/src/example archive package list.""" + + def __init__( + self, + flavor: str, + os_name, + target, + version, + base, + subarchives=None, + modules=None, + all_extra=False, + is_include_base_package: bool = True, + timeout=(5, 5), + ): + self.flavor: str = flavor + self.target = target + self.os_name = os_name + self.base = base + self.logger = getLogger("aqt.archives") + super(SrcDocExamplesArchives, self).__init__( + os_name, + target, + version, + arch=self.flavor, + base=base, + subarchives=subarchives, + modules=modules, + all_extra=all_extra, + is_include_base_package=is_include_base_package, + timeout=timeout, + ) + + def _arch_ext(self) -> str: + return "_" + QtRepoProperty.sde_ext(self.version) + + def _base_module_name(self) -> str: + """ + This is the name for the base Qt Src/Doc/Example module, whose PackageUpdate.Name + property would be 'qt.123.examples' or 'qt.qt1.123.examples' for Qt 1.2.3 examples. + """ + return self.flavor # src | doc | examples + + def _module_name_suffix(self, module: str) -> str: + return f"{self.flavor}.{module}" + + def get_target_config(self) -> TargetConfig: + """Get target configuration. + + :return tuple of three parameter, "src_doc_examples", target and arch + """ + return TargetConfig("src_doc_examples", self.target, self.arch, self.os_name) + + def _get_archives(self): + name = f"qt{self.version.major}_{self._version_str()}{self._arch_ext()}" + self._get_archives_base(name, self._target_packages()) + + def help_msg(self, missing_modules: Optional[List[str]] = None) -> List[str]: + _missing_modules: List[str] = missing_modules or [] + cmd_type = "example" if self.flavor == "examples" else self.flavor + base_cmd = f"aqt list-{cmd_type} {self.os_name} {self.version}" + mods = f"Please use '{base_cmd} --modules' to show modules available." + has_non_base_pkg: bool = len(list(_missing_modules)) > 1 + messages = [] + if has_non_base_pkg: + messages.append(mods) + return messages + + +class ToolArchives(QtArchives): + """Hold tool archive package list + when installing mingw tool, argument would be + ToolArchive(windows, desktop, 4.9.1-3, mingw) + when installing ifw tool, argument would be + ToolArchive(linux, desktop, 3.1.1, ifw) + """ + + def __init__( + self, + os_name: str, + target: str, + tool_name: str, + base: str, + version_str: Optional[str] = None, + arch: str = "", + timeout: Tuple[float, float] = (5, 5), + ): + self.tool_name = tool_name + self.os_name = os_name + self.logger = getLogger("aqt.archives") + self.tool_version_str: Optional[str] = version_str + super(ToolArchives, self).__init__( + os_name=os_name, + target=target, + version_str="0.0.1", # dummy value + arch=arch, + base=base, + timeout=timeout, + ) + + def __str__(self): + return f"ToolArchives(tool_name={self.tool_name}, version={self.version}, arch={self.arch})" + + def handle_missing_updates_xml(self, e: ArchiveDownloadError): + msg = f"Failed to locate XML data for the tool '{self.tool_name}'." + help_msg = f"Please use 'aqt list-tool {self.os_name} {self.target}' to show tools available." + raise ArchiveListError(msg, suggested_action=[help_msg]) from e + + def _get_archives(self): + self._get_archives_base(self.tool_name, None) + + def _parse_update_xml(self, os_target_folder: str, update_xml_text: str, *ignored: Any) -> None: + update_xml = Updates.fromstring(self.base, update_xml_text) + self._append_tool_update(os_target_folder, update_xml, self.arch, self.tool_version_str) + + def help_msg(self, *args) -> List[str]: + return [f"Please use 'aqt list-tool {self.os_name} {self.target} {self.tool_name}' to show tool variants available."] + + def get_target_config(self) -> TargetConfig: + """Get target configuration. + + :return tuple of three parameter, "Tools", target and arch + """ + return TargetConfig("Tools", self.target, self.arch, self.os_name) diff --git a/python/py313/Lib/site-packages/aqt/commercial.py b/python/py313/Lib/site-packages/aqt/commercial.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1dc5e17423aaafabf9b69001d7f0639450afe1 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/commercial.py @@ -0,0 +1,395 @@ +#!/usr/bin/env python +# +# Copyright (C) 2025 Alexandre Poumaroux, Hiroshi Miura +# +# 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. +import json +import os +from dataclasses import dataclass +from logging import Logger, getLogger +from pathlib import Path +from typing import List, Optional + +from defusedxml import ElementTree + +from aqt.exceptions import DiskAccessNotPermitted +from aqt.helper import ( + Settings, + download_installer, + extract_auth, + get_os_name, + get_qt_account_path, + get_qt_installer_name, + prepare_installer, + safely_run, + safely_run_save_output, +) +from aqt.metadata import Version + + +@dataclass +class QtPackageInfo: + name: str + displayname: str + version: str + + +class QtPackageManager: + def __init__( + self, arch: str, version: Version, target: str, username: Optional[str] = None, password: Optional[str] = None + ): + self.arch = arch + self.version = version + self.target = target + self.cache_dir = self._get_cache_dir() + self.packages: List[QtPackageInfo] = [] + self.username = username + self.password = password + self.logger = getLogger("aqt.commercial") + + def _get_cache_dir(self) -> Path: + """Create and return cache directory path.""" + base_cache = Settings.qt_installer_cache_path + cache_path = os.path.join(base_cache, self.target, self.arch, str(self.version)) + Path(cache_path).mkdir(parents=True, exist_ok=True) + return Path(cache_path) + + def _get_cache_file(self) -> Path: + """Get the cache file path.""" + return self.cache_dir / "packages.json" + + def _save_to_cache(self) -> None: + """Save packages information to cache.""" + cache_data = [{"name": pkg.name, "displayname": pkg.displayname, "version": pkg.version} for pkg in self.packages] + + with open(self._get_cache_file(), "w") as f: + json.dump(cache_data, f, indent=2) + + def _load_from_cache(self) -> bool: + """Load packages information from cache if available.""" + cache_file = self._get_cache_file() + if not cache_file.exists(): + return False + + try: + with open(cache_file, "r") as f: + cache_data = json.load(f) + self.packages = [ + QtPackageInfo(name=pkg["name"], displayname=pkg["displayname"], version=pkg["version"]) + for pkg in cache_data + ] + return True + except (json.JSONDecodeError, KeyError): + return False + + def _parse_packages_xml(self, xml_content: str) -> None: + """Parse packages XML content and extract package information using defusedxml.""" + try: + # Use defusedxml.ElementTree to safely parse the XML content + root = ElementTree.fromstring(xml_content) + self.packages = [] + + # Find all package elements using XPath-like expression + # Note: defusedxml supports a subset of XPath + for pkg in root.findall(".//package"): + name = pkg.get("name", "") + displayname = pkg.get("displayname", "") + version = pkg.get("version", "") + + if all([name, displayname, version]): # Ensure all required attributes are present + self.packages.append(QtPackageInfo(name=name, displayname=displayname, version=version)) + except ElementTree.ParseError as e: + raise RuntimeError(f"Failed to parse package XML: {e}") + + def _get_version_string(self) -> str: + """Get formatted version string for package names.""" + return f"{self.version.major}{self.version.minor}{self.version.patch}" + + def _get_base_package_name(self) -> str: + """Get the base package name for the current configuration.""" + version_str = self._get_version_string() + return f"qt.qt{self.version.major}.{version_str}" + + def gather_packages(self, installer_path: str) -> None: + """Gather package information using qt installer search command.""" + if self._load_from_cache(): + return + + version_str = self._get_version_string() + base_package = f"qt.qt{self.version.major}.{version_str}" + + cmd = [installer_path, "--accept-licenses", "--accept-obligations", "--confirm-command", "--default-answer"] + + if self.username and self.password: + cmd.extend(["--email", self.username, "--pw", self.password]) + + cmd.append("search") + cmd.append(base_package) + + try: + self.logger.info(f"Running: {cmd}") + output = safely_run_save_output(cmd, Settings.qt_installer_timeout) + + # Handle both string and CompletedProcess outputs + output_text = output.stdout if hasattr(output, "stdout") else str(output) + + # Extract the XML portion from the output + xml_start = output_text.find("") + xml_end = output_text.find("") + len("") + + if xml_start != -1 and xml_end != -1: + xml_content = output_text[xml_start:xml_end] + self._parse_packages_xml(xml_content) + self._save_to_cache() + else: + # Log the actual output for debugging + self.logger.debug(f"Installer output: {output_text}") + raise RuntimeError("Failed to find package information in installer output") + + except Exception as e: + raise RuntimeError(f"Failed to get package information: {str(e)}") + + def get_install_command(self, modules: Optional[List[str]], temp_dir: str) -> List[str]: + """Generate installation command based on requested modules.""" + package_name = f"{self._get_base_package_name()}.{self.arch}" + cmd = ["install", package_name] + + # No modules requested, return base package only + if not modules: + return cmd + + # Ensure package cache exists + self.gather_packages(temp_dir) + + if "all" in modules: + # Find all addon and direct module packages + for pkg in self.packages: + if f"{self._get_base_package_name()}.addons." in pkg.name or pkg.name.startswith( + f"{self._get_base_package_name()}." + ): + module_name = pkg.name.split(".")[-1] + if module_name != self.arch: # Skip the base package + cmd.append(pkg.name) + else: + # Add specifically requested modules that exist in either format + for module in modules: + addon_name = f"{self._get_base_package_name()}.addons.{module}" + direct_name = f"{self._get_base_package_name()}.{module}" + + # Check if either package name exists + matching_pkg = next( + (pkg.name for pkg in self.packages if pkg.name == addon_name or pkg.name == direct_name), None + ) + + if matching_pkg: + cmd.append(matching_pkg) + + return cmd + + +class CommercialInstaller: + """Qt Commercial installer that handles module installation and package management.""" + + def __init__( + self, + target: str, + arch: Optional[str], + version: Optional[str], + username: Optional[str] = None, + password: Optional[str] = None, + output_dir: Optional[str] = None, + logger: Optional[Logger] = None, + base_url: str = "https://download.qt.io", + override: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + no_unattended: bool = False, + dry_run: bool = False, + ): + self.override = override + self.target = target + self.arch = arch or "" + self.version = Version(version) if version else Version("0.0.0") + self.output_dir = output_dir + self.logger = logger or getLogger(__name__) + self.base_url = base_url + self.modules = modules + self.no_unattended = no_unattended + self.dry_run = dry_run + + # Extract credentials from override if present + if override: + extracted_username, extracted_password, self.override = extract_auth(override) + self.username = extracted_username or username + self.password = extracted_password or password + else: + self.username = username + self.password = password + + # Set OS-specific properties + self.os_name = get_os_name() + self._installer_filename = get_qt_installer_name() + self.qt_account = get_qt_account_path() + self.package_manager = QtPackageManager(self.arch, self.version, self.target, self.username, self.password) + + @staticmethod + def get_auto_answers() -> str: + """Get auto-answer options from settings.""" + settings_map = { + "OperationDoesNotExistError": Settings.qt_installer_operationdoesnotexisterror, + "OverwriteTargetDirectory": Settings.qt_installer_overwritetargetdirectory, + "stopProcessesForUpdates": Settings.qt_installer_stopprocessesforupdates, + "installationErrorWithCancel": Settings.qt_installer_installationerrorwithcancel, + "installationErrorWithIgnore": Settings.qt_installer_installationerrorwithignore, + "AssociateCommonFiletypes": Settings.qt_installer_associatecommonfiletypes, + "telemetry-question": Settings.qt_installer_telemetry, + } + + answers = [] + for key, value in settings_map.items(): + answers.append(f"{key}={value}") + + return ",".join(answers) + + @staticmethod + def build_command( + installer_path: str, + override: Optional[List[str]] = None, + username: Optional[str] = None, + password: Optional[str] = None, + output_dir: Optional[str] = None, + no_unattended: bool = False, + ) -> List[str]: + """Build the installation command with proper safeguards.""" + cmd = [installer_path] + + # Add unattended flags unless explicitly disabled + if not no_unattended: + cmd.extend(["--accept-licenses", "--accept-obligations", "--confirm-command"]) + + # Add authentication if provided + if username and password: + cmd.extend(["--email", username, "--pw", password]) + + if override: + # When using override, still include unattended flags unless disabled + cmd.extend(override) + return cmd + + # Add output directory if specified + if output_dir: + cmd.extend(["--root", str(Path(output_dir).resolve())]) + + # Add auto-answer options from settings + auto_answers = CommercialInstaller.get_auto_answers() + if auto_answers: + cmd.extend(["--auto-answer", auto_answers]) + + return cmd + + def install(self) -> None: + """Run the Qt installation process.""" + if ( + not self.qt_account.exists() + and (not self.username or not self.password) + and not os.environ.get("QT_INSTALLER_JWT_TOKEN") + ): + raise RuntimeError( + "No Qt account credentials found. Provide username and password or ensure qtaccount.ini exists." + ) + + # Setup cache directory + cache_path = Path(Settings.qt_installer_cache_path) + cache_path.mkdir(parents=True, exist_ok=True) + + # Setup output directory and validate access + output_dir = Path(self.output_dir) if self.output_dir else Path(os.getcwd()) / "Qt" + version_dir = output_dir / str(self.version) + qt_base_dir = output_dir + + if qt_base_dir.exists(): + if Settings.qt_installer_overwritetargetdirectory.lower() == "yes": + self.logger.warning(f"Target directory {qt_base_dir} exists - removing as overwrite is enabled") + try: + import shutil + + if version_dir.exists(): + shutil.rmtree(version_dir) + except (OSError, PermissionError) as e: + raise DiskAccessNotPermitted(f"Failed to remove existing version directory {version_dir}: {str(e)}") + + # Setup temp directory + temp_dir = Settings.qt_installer_temp_path + temp_path = Path(temp_dir) + if not temp_path.exists(): + temp_path.mkdir(parents=True, exist_ok=True) + else: + Settings.qt_installer_cleanup() + installer_path = temp_path / self._installer_filename + + self.logger.info(f"Downloading Qt installer to {installer_path}") + timeout = (Settings.connection_timeout, Settings.response_timeout) + download_installer(self.base_url, self._installer_filename, installer_path, timeout) + installer_path = prepare_installer(installer_path, self.os_name) + + try: + if self.override: + if not self.username or not self.password: + self.username, self.password, self.override = extract_auth(self.override) + + cmd: list[str] = self.build_command( + str(installer_path), + override=self.override, + no_unattended=self.no_unattended, + username=self.username, + password=self.password, + ) + else: + # Initialize package manager and gather packages + self.package_manager.gather_packages(str(installer_path)) + + base_cmd = self.build_command( + str(installer_path.absolute()), + username=self.username, + password=self.password, + output_dir=str(qt_base_dir.absolute()), + no_unattended=self.no_unattended, + ) + + install_cmd = self.package_manager.get_install_command(self.modules, temp_dir) + cmd = [*base_cmd, *install_cmd] + + log_cmd = cmd.copy() + for i in range(len(log_cmd) - 1): + if log_cmd[i] == "--email" or log_cmd[i] == "--pw": + log_cmd[i + 1] = "***" + + if not self.dry_run: + self.logger.info(f"Running: {log_cmd}") + safely_run(cmd, Settings.qt_installer_timeout) + else: + self.logger.info(f"Would run: {log_cmd}") + + except Exception as e: + self.logger.error(f"Installation failed: {str(e)}") + raise + finally: + self.logger.info("Qt installation completed successfully") + + def _get_package_name(self) -> str: + qt_version = f"{self.version.major}{self.version.minor}{self.version.patch}" + return f"qt.qt{self.version.major}.{qt_version}.{self.arch}" diff --git a/python/py313/Lib/site-packages/aqt/exceptions.py b/python/py313/Lib/site-packages/aqt/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c896f371d1fa61a615dd5b5f3ad3a4e674567334 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/exceptions.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2019-2021 Hiroshi Miura +# +# 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 Any, List, Optional + +DOCS_CONFIG = "https://aqtinstall.readthedocs.io/en/stable/configuration.html#configuration" + + +class AqtException(Exception): + def __init__( + self, *args, suggested_action: Optional[List[str]] = None, should_show_help: bool = False, **kwargs: Any + ) -> None: + self.suggested_action: List[str] = suggested_action or [] + self.should_show_help: bool = should_show_help or False + super(AqtException, self).__init__(*args, **kwargs) + + def __format__(self, format_spec: str) -> str: + base_msg = "{}".format(super(AqtException, self).__format__(format_spec)) + if not self.suggested_action: + return base_msg + return f"{base_msg}\n{self._format_suggested_follow_up()}" + + def _format_suggested_follow_up(self) -> str: + return ("=" * 30 + "Suggested follow-up:" + "=" * 30 + "\n") + "\n".join( + ["* " + suggestion for suggestion in self.suggested_action] + ) + + def append_suggested_follow_up(self, suggestions: List[str]) -> None: + self.suggested_action.extend(suggestions) + + +class ArchiveDownloadError(AqtException): + pass + + +class ArchiveChecksumError(ArchiveDownloadError): + pass + + +class ChecksumDownloadFailure(ArchiveDownloadError): + def __init__(self, *args, suggested_action: Optional[List[str]] = None, **kwargs) -> None: + if suggested_action is None: + suggested_action = [] + suggested_action.extend( + [ + "Check your internet connection", + "Consider modifying `requests.max_retries_to_retrieve_hash` in settings.ini", + f"Consider modifying `mirrors.trusted_mirrors` in settings.ini (see {DOCS_CONFIG})", + ] + ) + super(ChecksumDownloadFailure, self).__init__( + *args, suggested_action=suggested_action, should_show_help=True, **kwargs + ) + + +class ArchiveConnectionError(AqtException): + pass + + +class ArchiveListError(AqtException): + pass + + +class NoPackageFound(AqtException): + pass + + +class EmptyMetadata(AqtException): + pass + + +class CliInputError(AqtException): + pass + + +class CliKeyboardInterrupt(AqtException): + pass + + +class ArchiveExtractionError(AqtException): + pass + + +class UpdaterError(AqtException): + pass + + +class OutOfMemory(AqtException): + pass + + +class OutOfDiskSpace(AqtException): + pass + + +class DiskAccessNotPermitted(AqtException): + pass diff --git a/python/py313/Lib/site-packages/aqt/helper.py b/python/py313/Lib/site-packages/aqt/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..787b68616c9e6f87e7a7e14f9b006d489e3c4c01 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/helper.py @@ -0,0 +1,786 @@ +#!/usr/bin/env python +# +# Copyright (C) 2019-2021 Hiroshi Miura +# +# 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. +import binascii +import hashlib +import logging.config +import os +import platform +import posixpath +import secrets +import shutil +import subprocess +import sys +import uuid +from configparser import ConfigParser +from logging import Handler, getLogger +from logging.handlers import QueueListener +from pathlib import Path +from threading import Lock +from typing import Any, Callable, Dict, Generator, List, Optional, TextIO, Tuple, Union +from urllib.parse import urlparse +from xml.etree.ElementTree import Element + +import humanize +import requests +import requests.adapters +from bs4 import BeautifulSoup +from defusedxml import ElementTree + +from aqt.exceptions import ( + ArchiveChecksumError, + ArchiveConnectionError, + ArchiveDownloadError, + ArchiveListError, + ChecksumDownloadFailure, +) + + +def get_os_name() -> str: + system = sys.platform.lower() + if system == "darwin": + return "mac" + if system == "linux": + return "linux" + if system in ("windows", "win32"): # Accept both windows and win32 + return "windows" + raise ValueError(f"Unsupported operating system: {system}") + + +def get_os_arch() -> str: + """ + Returns a simplified os-arch string for the current system + """ + os_name = get_os_name() + + machine = platform.machine().lower() + if machine in ["x86_64", "amd64"]: + arch = "x64" + elif machine in ["arm64", "aarch64"]: + arch = "arm64" + else: + arch = "x64" # Default to x64 for unknown architectures + + return f"{os_name}-{arch}" + + +def get_qt_local_folder_path() -> Path: + os_name = get_os_name() + if os_name == "windows": + appdata = os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming")) + return Path(appdata) / "Qt" + if os_name == "mac": + return Path.home() / "Library" / "Application Support" / "Qt" + return Path.home() / ".local" / "share" / "Qt" + + +def get_qt_account_path() -> Path: + return get_qt_local_folder_path() / "qtaccount.ini" + + +def get_qt_installers() -> dict[str, str]: + """ + Extracts Qt installer information from {Settings.baseurl}/official_releases/online_installers/ + Maps OS types and architectures to their respective installer filenames + Returns: + dict: Mapping of OS identifiers to installer filenames with appropriate aliases + """ + url = f"{Settings.baseurl}/official_releases/online_installers/" + + try: + response = requests.get(url, timeout=Settings.response_timeout) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "html.parser") + + installers = {} + + os_types = ["windows", "linux", "mac"] + + for link in soup.find_all("a"): + filename = link.text.strip() + + if "Parent Directory" in filename or not any(ext in filename.lower() for ext in [".exe", ".dmg", ".run"]): + continue + + for os_type in os_types: + if os_type.lower() in filename.lower(): + # Found an OS match, now look for architecture + if "arm64" in filename.lower(): + installers[f"{os_type}-arm64"] = filename + elif "x64" in filename.lower(): + installers[f"{os_type}-x64"] = filename + # Also add generic OS entry for x64 variants of Windows and Linux + if os_type in ["windows", "linux"]: + installers[os_type] = filename + else: + # Handle case with no explicit architecture + # Most likely for macOS which might just say "mac" without arch + installers[os_type] = filename + + return installers + + except requests.exceptions.RequestException as e: + print(f"Error fetching installer data: {e}") + return {} + except Exception as e: + print(f"Unexpected error processing installer data: {e}") + return {} + + +def get_qt_installer_name() -> str: + installer_dict = get_qt_installers() + return installer_dict[get_os_arch()] + + +def get_qt_installer_path() -> Path: + return get_qt_local_folder_path() / get_qt_installer_name() + + +def get_default_local_cache_path() -> Path: + os_name = get_os_name() + if os_name == "windows": + appdata = os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming")) + return Path(appdata) / "aqt" / "cache" + if os_name == "mac": + return Path.home() / "Library" / "Application Support" / "aqt" / "cache" + return Path.home() / ".local" / "share" / "aqt" / "cache" + + +def get_default_local_temp_path() -> Path: + os_name = get_os_name() + if os_name == "windows": + appdata = os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming")) + return Path(appdata) / "aqt" / "tmp" + if os_name == "mac": + return Path.home() / "Library" / "Application Support" / "aqt" / "tmp" + return Path.home() / ".local" / "share" / "aqt" / "tmp" + + +def _get_meta(url: str) -> requests.Response: + return requests.get(url + ".meta4") + + +def _check_content_type(ct: str) -> bool: + candidate = ["application/metalink4+xml", "text/plain"] + return any(ct.startswith(t) for t in candidate) + + +def getUrl(url: str, timeout: Tuple[float, float], expected_hash: Optional[bytes] = None) -> str: + """ + Gets a file from `url` via HTTP GET. + + No caller should call this function without providing an expected_hash, unless + the caller is `get_hash`, which cannot know what the expected hash should be. + """ + logger = getLogger("aqt.helper") + with requests.sessions.Session() as session: + retries = requests.adapters.Retry( + total=Settings.max_retries_on_connection_error, backoff_factor=Settings.backoff_factor + ) + adapter = requests.adapters.HTTPAdapter(max_retries=retries) + session.mount("http://", adapter) + session.mount("https://", adapter) + try: + r = session.get(url, allow_redirects=False, timeout=timeout) + num_redirects = 0 + while 300 < r.status_code < 309 and num_redirects < 10: + num_redirects += 1 + logger.debug("Asked to redirect({}) to: {}".format(r.status_code, r.headers["Location"])) + newurl = altlink(r.url, r.headers["Location"]) + logger.info("Redirected: {}".format(urlparse(newurl).hostname)) + r = session.get(newurl, stream=True, timeout=timeout) + except ( + ConnectionResetError, + requests.exceptions.ConnectionError, + requests.exceptions.Timeout, + ) as e: + raise ArchiveConnectionError(f"Failure to connect to {url}: {type(e).__name__}") from e + else: + if r.status_code != 200: + msg = f"Failed to retrieve file at {url}\nServer response code: {r.status_code}, reason: {r.reason}" + raise ArchiveDownloadError(msg) + result: str = r.text + filename = url.split("/")[-1] + _kwargs = {"usedforsecurity": False} if sys.version_info >= (3, 9) else {} + if Settings.hash_algorithm == "sha256": + actual_hash = hashlib.sha256(bytes(result, "utf-8"), **_kwargs).digest() + elif Settings.hash_algorithm == "sha1": + actual_hash = hashlib.sha1(bytes(result, "utf-8"), **_kwargs).digest() + elif Settings.hash_algorithm == "md5": + actual_hash = hashlib.md5(bytes(result, "utf-8"), **_kwargs).digest() + else: + raise ArchiveChecksumError(f"Unknown hash algorithm: {Settings.hash_algorithm}.\nPlease check settings.ini") + if expected_hash is not None and expected_hash != actual_hash: + raise ArchiveChecksumError( + f"Downloaded file {filename} is corrupted! Detect checksum error.\n" + f"Expect {expected_hash.hex()}: {url}\n" + f"Actual {actual_hash.hex()}: {filename}" + ) + return result + + +def downloadBinaryFile(url: str, out: Path, hash_algo: str, exp: Optional[bytes], timeout: Tuple[float, float]) -> None: + logger = getLogger("aqt.helper") + filename = Path(url).name + with requests.sessions.Session() as session: + retries = requests.adapters.Retry( + total=Settings.max_retries_on_connection_error, backoff_factor=Settings.backoff_factor + ) + adapter = requests.adapters.HTTPAdapter(max_retries=retries) + session.mount("http://", adapter) + session.mount("https://", adapter) + try: + r = session.get(url, allow_redirects=False, stream=True, timeout=timeout) + if 300 < r.status_code < 309: + logger.debug("Asked to redirect({}) to: {}".format(r.status_code, r.headers["Location"])) + newurl = altlink(r.url, r.headers["Location"]) + logger.info("Redirected: {}".format(urlparse(newurl).hostname)) + r = session.get(newurl, stream=True, timeout=timeout) + except requests.exceptions.ConnectionError as e: + raise ArchiveConnectionError(f"Connection error: {e.args}") from e + except requests.exceptions.Timeout as e: + raise ArchiveConnectionError(f"Connection timeout: {e.args}") from e + else: + if sys.version_info >= (3, 9): + hash = hashlib.new(hash_algo, usedforsecurity=False) + else: + hash = hashlib.new(hash_algo) + try: + with open(out, "wb") as fd: + for chunk in r.iter_content(chunk_size=8196): + fd.write(chunk) + hash.update(chunk) + fd.flush() + except requests.exceptions.ReadTimeout as e: + raise ArchiveConnectionError(f"Read timeout: {e.args}") from e + except Exception as e: + raise ArchiveDownloadError(f"Download of {filename} has error: {e}") from e + if exp is not None and hash.digest() != exp: + raise ArchiveChecksumError( + f"Downloaded file {filename} is corrupted! Detect checksum error.\n" + f"Expect {exp.hex()}: {url}\n" + f"Actual {hash.digest().hex()}: {out.name}" + ) + + +def retry_on_errors(action: Callable[[], Any], acceptable_errors: Tuple, num_retries: int, name: str) -> Any: + logger = getLogger("aqt.helper") + for i in range(num_retries): + try: + retry_msg = f": attempt #{1 + i}" if i > 0 else "" + logger.info(f"{name}{retry_msg}...") + ret = action() + if i > 0: + logger.info(f"Success on attempt #{1 + i}: {name}") + return ret + except acceptable_errors as e: + if i < num_retries - 1: + continue # just try again + raise e from e + + +def retry_on_bad_connection(function: Callable[[str], Any], base_url: str) -> Any: + logger = getLogger("aqt.helper") + fallback_url = secrets.choice(Settings.fallbacks) + try: + return function(base_url) + except ArchiveConnectionError: + logger.warning(f"Connection to '{base_url}' failed. Retrying with fallback '{fallback_url}'.") + return function(fallback_url) + + +def iter_list_reps(_list: List, num_reps: int) -> Generator: + list_index = 0 + for i in range(num_reps): + yield _list[list_index] + list_index += 1 + if list_index >= len(_list): + list_index = 0 + + +def get_hash(archive_path: str, algorithm: str, timeout: Tuple[float, float]) -> bytes: + """ + Downloads a checksum and unhexlifies it to a `bytes` object, guaranteed to be the right length. + Raises ChecksumDownloadFailure if the download failed, or if the checksum was un unexpected length. + + :param archive_path: The path to the file that we want to check, not the path to the checksum. + :param algorithm: sha256 is the only safe value to use here. + :param timeout: The timeout used by getUrl. + :return: A checksum in `bytes` + """ + logger = getLogger("aqt.helper") + hash_lengths = {"sha256": 64, "sha1": 40, "md5": 32} + for base_url in iter_list_reps(Settings.trusted_mirrors, Settings.max_retries_to_retrieve_hash): + url = posixpath.join(base_url, f"{archive_path}.{algorithm}") + logger.debug(f"Attempt to download checksum at {url}") + try: + r = getUrl(url, timeout) + # sha256 & md5 files are: "some_hash archive_filename" + _hash = r.split(" ")[0] + if len(_hash) == hash_lengths[algorithm]: + return binascii.unhexlify(_hash) + except (ArchiveConnectionError, ArchiveDownloadError, binascii.Incomplete, binascii.Error): + pass + filename = archive_path.split("/")[-1] + raise ChecksumDownloadFailure( + f"Failed to download checksum for the file '{filename}' from mirrors '{Settings.trusted_mirrors}" + ) + + +def altlink(url: str, alt: str) -> str: + """ + Blacklisting redirected(alt) location based on Settings. Blacklist configuration. + When found black url, then try download an url + .meta4 that is a metalink version4 + xml file, parse it and retrieve the best alternative url. + """ + logger = getLogger("aqt.helper") + if not any(alt.startswith(b) for b in Settings.blacklist): + return alt + try: + m = _get_meta(url) + except requests.exceptions.ConnectionError: + logger.error("Got connection error. Fall back to recovery plan...") + return alt + else: + # Expected response->'application/metalink4+xml; charset=utf-8' + if not _check_content_type(m.headers["content-type"]): + logger.error("Unexpected meta4 response;content-type: {}".format(m.headers["content-type"])) + return alt + try: + mirror_xml = ElementTree.fromstring(m.text) + meta_urls: Dict[str, str] = {} + for f in mirror_xml.iter("{urn:ietf:params:xml:ns:metalink}file"): + for u in f.iter("{urn:ietf:params:xml:ns:metalink}url"): + meta_urls[u.attrib["priority"]] = u.text + mirrors = [meta_urls[i] for i in sorted(meta_urls.keys(), key=lambda x: int(x))] + except Exception: + exc_info = sys.exc_info() + logger.error("Unexpected meta4 file; parse error: {}".format(exc_info[1])) + return alt + else: + # Return first priority item which is not blacklist in mirrors list, + # if not found then return alt in default + try: + return next(mirror for mirror in mirrors if not any(mirror.startswith(b) for b in Settings.blacklist)) + except StopIteration: + return alt + + +class MyQueueListener(QueueListener): + def __init__(self, queue) -> None: + handlers: List[Handler] = [] + super().__init__(queue, *handlers) + + def handle(self, record) -> None: + """ + Handle a record from subprocess. + Override logger name then handle at proper logger. + """ + record = self.prepare(record) + logger = getLogger("aqt.installer") + record.name = "aqt.installer" + logger.handle(record) + + +def ssplit(data: str) -> Generator[str, None, None]: + for element in data.split(","): + yield element.strip() + + +def xml_to_modules( + xml_text: str, + predicate: Callable[[Element], bool], +) -> Dict[str, Dict[str, str]]: + """Converts an XML document to a dict of `PackageUpdate` dicts, indexed by `Name` attribute. + Only report elements that satisfy `predicate(element)`. + Reports all keys available in the PackageUpdate tag as strings. + + :param xml_text: The entire contents of an xml file + :param predicate: A function that decides which elements to keep or discard + """ + try: + parsed_xml = ElementTree.fromstring(xml_text) + except ElementTree.ParseError as perror: + raise ArchiveListError(f"Downloaded metadata is corrupted. {perror}") from perror + packages: Dict[str, Dict[str, str]] = {} + for packageupdate in parsed_xml.iter("PackageUpdate"): + if not predicate(packageupdate): + continue + name = packageupdate.find("Name").text + packages[name] = {} + for child in packageupdate: + if child.tag == "UpdateFile": + for attr in "CompressedSize", "UncompressedSize": + if attr not in child.attrib: + continue + packages[name][attr] = humanize.naturalsize(child.attrib[attr], gnu=True) + else: + packages[name][child.tag] = child.text + return packages + + +class MyConfigParser(ConfigParser): + def getlist(self, section: str, option: str, fallback: List[str] = []) -> List[str]: + value = self.get(section, option, fallback=None) + if value is None: + return fallback + try: + result = list(filter(None, (x.strip() for x in value.splitlines()))) + except Exception: + result = fallback + return result + + def getlistint(self, section: str, option: str, fallback: List[int] = []) -> List[int]: + try: + result = [int(x) for x in self.getlist(section, option)] + except Exception: + result = fallback + return result + + +class SettingsClass: + """ + Class to hold configuration and settings. + Actual values are stored in 'settings.ini' file. + """ + + # this class is Borg + _shared_state: Dict[str, Any] = { + "config": None, + "configfile": None, + "loggingconf": None, + "_ignore_hash_override": None, + "_lock": Lock(), + } + + def __init__(self) -> None: + self.config: Optional[ConfigParser] + self._lock: Lock + self._ignore_hash_override: Optional[bool] = None + self._initialize() + + def __new__(cls, *p, **k): + self = object.__new__(cls, *p, **k) + self.__dict__ = cls._shared_state + return self + + def _initialize(self) -> None: + """Initialize configuration if not already initialized.""" + if self.config is None: + with self._lock: + if self.config is None: + self.config = MyConfigParser() + self.configfile = os.path.join(os.path.dirname(__file__), "settings.ini") + self.loggingconf = os.path.join(os.path.dirname(__file__), "logging.ini") + self.config.read(self.configfile) + + logging.info(f"Cache folder: {self.qt_installer_cache_path}") + logging.info(f"Temp folder: {self.qt_installer_temp_path}") + + temp_dir = self.qt_installer_temp_path + temp_path = Path(temp_dir) + if not temp_path.exists(): + temp_path.mkdir(parents=True, exist_ok=True) + else: + self.qt_installer_cleanup() + + def _get_config(self) -> ConfigParser: + """Safe getter for config that ensures it's initialized.""" + self._initialize() + assert self.config is not None + return self.config + + def set_ignore_hash_for_session(self, value: bool) -> None: + """Override the INSECURE_NOT_FOR_PRODUCTION_ignore_hash setting for the current session without modifying config.""" + self._ignore_hash_override = value + + def load_settings(self, file: Optional[Union[str, TextIO]] = None) -> None: + if self.config is None: + return + + if file is not None: + if isinstance(file, str): + result = self.config.read(file) + if len(result) == 0: + raise IOError("Fails to load specified config file {}".format(file)) + self.configfile = file + else: + # passed through command line argparse.FileType("r") + self.config.read_file(file) + self.configfile = file.name + file.close() + else: + with open(self.configfile, "r") as f: + self.config.read_file(f) + + @property + def qt_installer_cache_path(self) -> str: + """Path for Qt installer cache.""" + config = self._get_config() + # If no cache_path or blank, return default without modifying config + if not config.has_option("qtofficial", "cache_path") or config.get("qtofficial", "cache_path").strip() == "": + return str(get_default_local_cache_path()) + return config.get("qtofficial", "cache_path") + + @property + def qt_installer_temp_path(self) -> str: + """Path for Qt installer cache.""" + config = self._get_config() + # If no cache_path or blank, return default without modifying config + if not config.has_option("qtofficial", "temp_path") or config.get("qtofficial", "temp_path").strip() == "": + return str(get_default_local_temp_path()) + return config.get("qtofficial", "temp_path") + + @property + def archive_download_location(self): + return self.config.get("aqt", "archive_download_location", fallback=".") + + @property + def always_keep_archives(self): + return self.config.getboolean("aqt", "always_keep_archives", fallback=False) + + @property + def concurrency(self): + """concurrency configuration. + + :return: concurrency + :rtype: int + """ + return self.config.getint("aqt", "concurrency", fallback=4) + + @property + def blacklist(self): + """list of sites in a blacklist + + :returns: list of site URLs(scheme and host part) + :rtype: List[str] + """ + return self.config.getlist("mirrors", "blacklist", fallback=[]) + + @property + def baseurl(self): + return self.config.get("aqt", "baseurl", fallback="https://download.qt.io") + + @property + def connection_timeout(self): + return self.config.getfloat("requests", "connection_timeout", fallback=3.5) + + @property + def response_timeout(self): + return self.config.getfloat("requests", "response_timeout", fallback=10) + + @property + def max_retries(self): + """Deprecated: please use `max_retries_on_connection_error` and `max_retries_on_checksum_error` instead!""" + return self.config.getfloat("requests", "max_retries", fallback=5) + + @property + def max_retries_on_connection_error(self): + return self.config.getfloat("requests", "max_retries_on_connection_error", fallback=self.max_retries) + + @property + def max_retries_on_checksum_error(self): + return self.config.getint("requests", "max_retries_on_checksum_error", fallback=int(self.max_retries)) + + @property + def max_retries_to_retrieve_hash(self): + return self.config.getint("requests", "max_retries_to_retrieve_hash", fallback=int(self.max_retries)) + + @property + def hash_algorithm(self): + return self.config.get("requests", "hash_algorithm", fallback="sha256") + + @property + def ignore_hash(self): + if self._ignore_hash_override is not None: + return self._ignore_hash_override + return self.config.getboolean("requests", "INSECURE_NOT_FOR_PRODUCTION_ignore_hash", fallback=False) + + @property + def backoff_factor(self): + return self.config.getfloat("requests", "retry_backoff", fallback=0.1) + + @property + def trusted_mirrors(self): + return self.config.getlist("mirrors", "trusted_mirrors", fallback=[self.baseurl]) + + @property + def fallbacks(self): + return self.config.getlist("mirrors", "fallbacks", fallback=[]) + + @property + def zipcmd(self): + return self.config.get("aqt", "7zcmd", fallback="7z") + + @property + def kde_patches(self): + return self.config.getlist("kde_patches", "patches", fallback=[]) + + @property + def print_stacktrace_on_error(self): + return self.config.getboolean("aqt", "print_stacktrace_on_error", fallback=False) + + @property + def min_module_size(self): + """ + Some modules in the Qt repository contain only empty directories. + We have found that these modules are no more than 40 bytes after decompression. + This setting is used to filter out these empty modules in `list-*` output. + """ + return self.config.getint("aqt", "min_module_size", fallback=41) + + # Qt Commercial Installer properties + @property + def qt_installer_timeout(self) -> int: + """Timeout for Qt commercial installer operations in seconds.""" + return self._get_config().getint("qtofficial", "installer_timeout", fallback=3600) + + @property + def qt_installer_operationdoesnotexisterror(self) -> str: + """Handle OperationDoesNotExistError in Qt installer.""" + return self._get_config().get("qtofficial", "operation_does_not_exist_error", fallback="Ignore") + + @property + def qt_installer_overwritetargetdirectory(self) -> str: + """Handle overwriting target directory in Qt installer.""" + return self._get_config().get("qtofficial", "overwrite_target_directory", fallback="No") + + @property + def qt_installer_stopprocessesforupdates(self) -> str: + """Handle stopping processes for updates in Qt installer.""" + return self._get_config().get("qtofficial", "stop_processes_for_updates", fallback="Cancel") + + @property + def qt_installer_installationerrorwithcancel(self) -> str: + """Handle installation errors with cancel option in Qt installer.""" + return self._get_config().get("qtofficial", "installation_error_with_cancel", fallback="Cancel") + + @property + def qt_installer_installationerrorwithignore(self) -> str: + """Handle installation errors with ignore option in Qt installer.""" + return self._get_config().get("qtofficial", "installation_error_with_ignore", fallback="Ignore") + + @property + def qt_installer_associatecommonfiletypes(self) -> str: + """Handle file type associations in Qt installer.""" + return self._get_config().get("qtofficial", "associate_common_filetypes", fallback="Yes") + + @property + def qt_installer_telemetry(self) -> str: + """Handle telemetry settings in Qt installer.""" + return self._get_config().get("qtofficial", "telemetry", fallback="No") + + @property + def qt_installer_unattended(self) -> bool: + """Control whether to use unattended installation flags.""" + return self._get_config().getboolean("qtofficial", "unattended", fallback=True) + + def qt_installer_cleanup(self) -> None: + """Clean tmp folder.""" + for item in Path(self.qt_installer_temp_path).iterdir(): + if item.is_dir(): + shutil.rmtree(item) + else: + item.unlink() + + +Settings = SettingsClass() + + +def setup_logging(env_key="LOG_CFG"): + config = os.getenv(env_key, None) + if config is not None and os.path.exists(config): + Settings.loggingconf = config + logging.config.fileConfig(Settings.loggingconf) + + +def safely_run(cmd: List[str], timeout: int) -> None: + try: + subprocess.run(cmd, shell=False, timeout=timeout) + except Exception: + raise + + +def safely_run_save_output(cmd: List[str], timeout: int) -> Any: + try: + result = subprocess.run(cmd, shell=False, capture_output=True, text=True, timeout=timeout) + return result + except Exception: + raise + + +def extract_auth(args: List[str]) -> Tuple[Union[str, None], Union[str, None], Union[List[str], None]]: + username = None + password = None + i = 0 + while i < len(args): + if args[i] == "--email": + if i + 1 < len(args): + username = args[i + 1] + del args[i : i + 2] + else: + del args[i] + continue + elif args[i] == "--pw": + if i + 1 < len(args): + password = args[i + 1] + del args[i : i + 2] + else: + del args[i] + continue + i += 1 + return username, password, args + + +def download_installer(base_url: str, installer_filename: str, target_path: Path, timeout: Tuple[float, float]) -> None: + base_path = f"official_releases/online_installers/{installer_filename}" + url = f"{base_url}/{base_path}" + try: + hash = get_hash(base_path, Settings.hash_algorithm, timeout) + downloadBinaryFile(url, target_path, Settings.hash_algorithm, hash, timeout=timeout) + except Exception as e: + raise RuntimeError(f"Failed to download installer: {e}") + + +def prepare_installer(installer_path: Path, os_name: str) -> Path: + """ + Prepares the installer for execution. This may involve setting the correct permissions or + extracting the installer if it's packaged. Returns the path to the installer executable. + """ + if os_name == "linux": + os.chmod(installer_path, 0o500) + return installer_path + elif os_name == "mac": + volume_path = Path(f"/Volumes/{str(uuid.uuid4())}") + subprocess.run( + ["hdiutil", "attach", str(installer_path), "-mountpoint", str(volume_path)], + stdout=subprocess.DEVNULL, + check=True, + ) + try: + src_app_name = next(volume_path.glob("*.app")).name + dst_app_path = installer_path.with_suffix(".app") + shutil.copytree(volume_path / src_app_name, dst_app_path) + finally: + subprocess.run(["hdiutil", "detach", str(volume_path), "-force"], stdout=subprocess.DEVNULL, check=True) + return dst_app_path / "Contents" / "MacOS" / Path(src_app_name).stem + else: + return installer_path diff --git a/python/py313/Lib/site-packages/aqt/installer.py b/python/py313/Lib/site-packages/aqt/installer.py new file mode 100644 index 0000000000000000000000000000000000000000..d958e13fe6c2d34b2b96f10e875e0bdeb70b4a69 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/installer.py @@ -0,0 +1,1708 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2018 Linus Jahn +# Copyright (C) 2019-2025 Hiroshi Miura +# Copyright (C) 2020, Aurélien Gâteau +# +# 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. + +import argparse +import errno +import gc +import multiprocessing +import os +import platform +import posixpath +import re +import signal +import subprocess +import sys +import tarfile +import time +import zipfile +from logging import getLogger +from logging.handlers import QueueHandler +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import List, Optional, Tuple, cast + +import aqt +from aqt.archives import QtArchives, QtPackage, SrcDocExamplesArchives, ToolArchives +from aqt.commercial import CommercialInstaller +from aqt.exceptions import ( + AqtException, + ArchiveChecksumError, + ArchiveDownloadError, + ArchiveExtractionError, + ArchiveListError, + CliInputError, + CliKeyboardInterrupt, + DiskAccessNotPermitted, + OutOfDiskSpace, + OutOfMemory, +) +from aqt.helper import ( + MyQueueListener, + Settings, + download_installer, + downloadBinaryFile, + extract_auth, + get_hash, + get_os_name, + get_qt_installer_name, + prepare_installer, + retry_on_bad_connection, + retry_on_errors, + safely_run_save_output, + setup_logging, +) +from aqt.metadata import ArchiveId, MetadataFactory, QtRepoProperty, SimpleSpec, Version, show_list, suggested_follow_up +from aqt.updater import Updater, dir_for_version + +try: + import py7zr + + EXT7Z = False +except ImportError: + EXT7Z = True + + +class BaseArgumentParser(argparse.ArgumentParser): + """Global options and subcommand trick""" + + config: Optional[str] + func: object + + +class ListArgumentParser(BaseArgumentParser): + """List-* command parser arguments and options""" + + arch: Optional[str] + archives: List[str] + extension: str + extensions: str + host: str + last_version: str + latest_version: bool + long: bool + long_modules: List[str] + modules: List[str] + qt_version_spec: str + spec: str + target: str + email: Optional[str] + pw: Optional[str] + search_terms: Optional[str] + + +class ListToolArgumentParser(ListArgumentParser): + """List-tool command options""" + + tool_name: str + tool_version: str + + +class CommonInstallArgParser(BaseArgumentParser): + """Install-*/install common arguments""" + + target: str + host: str + + outputdir: Optional[str] + base: Optional[str] + timeout: Optional[float] + external: Optional[str] + internal: bool + keep: bool + archive_dest: Optional[str] + dry_run: bool + + +class InstallArgParser(CommonInstallArgParser): + """Install-qt arguments and options""" + + override: Optional[List[str]] + arch: Optional[str] + qt_version: str + qt_version_spec: str + version: Optional[str] + email: Optional[str] + pw: Optional[str] + operation_does_not_exist_error: str + overwrite_target_dir: str + stop_processes_for_updates: str + installation_error_with_cancel: str + installation_error_with_ignore: str + associate_common_filetypes: str + telemetry: str + + modules: Optional[List[str]] + archives: Optional[List[str]] + noarchives: bool + autodesktop: bool + + +class InstallToolArgParser(CommonInstallArgParser): + """Install-tool arguments and options""" + + tool_name: str + version: Optional[str] + tool_variant: Optional[str] + + +class Cli: + """CLI main class to parse command line argument and launch proper functions.""" + + __slot__ = ["parser", "combinations", "logger"] + + UNHANDLED_EXCEPTION_CODE = 254 + + def __init__(self) -> None: + parser = argparse.ArgumentParser( + prog="aqt", + description="Another unofficial Qt Installer.\naqt helps you install Qt SDK, tools, examples and others\n", + formatter_class=argparse.RawTextHelpFormatter, + add_help=True, + ) + parser.add_argument( + "-c", + "--config", + type=argparse.FileType("r"), + help="Configuration ini file.", + ) + subparsers = parser.add_subparsers( + title="subcommands", + description="aqt accepts several subcommands:\n" + "install-* subcommands are commands that install components\n" + "list-* subcommands are commands that show available components\n", + help="Please refer to each help message by using '--help' with each subcommand", + ) + self._make_all_parsers(subparsers) + parser.set_defaults(func=self.show_help) + self.parser = parser + + def run(self, arg=None) -> int: + args = self.parser.parse_args(arg) + self._setup_settings(args) + try: + args.func(args) + return 0 + except AqtException as e: + self.logger.error(format(e), exc_info=Settings.print_stacktrace_on_error) + if e.should_show_help: + self.show_help() + return 1 + except Exception as e: + # If we didn't account for it, and wrap it in an AqtException, it's a bug. + self.logger.exception(e) # Print stack trace + self.logger.error( + f"{self._format_aqt_version()}\n" + f"Working dir: `{os.getcwd()}`\n" + f"Arguments: `{sys.argv}` Host: `{platform.uname()}`\n" + "===========================PLEASE FILE A BUG REPORT===========================\n" + "You have discovered a bug in aqt.\n" + "Please file a bug report at https://github.com/miurahr/aqtinstall/issues\n" + "Please remember to include a copy of this program's output in your report." + ) + return Cli.UNHANDLED_EXCEPTION_CODE + + def _set_sevenzip(self, external: Optional[str]) -> Optional[str]: + sevenzip = external + fallback = Settings.zipcmd + if sevenzip is None: + if EXT7Z: + self.logger.warning(f"The py7zr module failed to load. Falling back to '{fallback}' for .7z extraction.") + self.logger.warning("You can use the '--external | -E' flags to select your own extraction tool.") + sevenzip = fallback + else: + # Just use py7zr + return None + try: + subprocess.run( + [sevenzip, "--help"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + return sevenzip + except FileNotFoundError as e: + qualifier = "Specified" if sevenzip == external else "Fallback" + raise CliInputError(f"{qualifier} 7zip command executable does not exist: '{sevenzip}'") from e + + @staticmethod + def _set_arch(arch: Optional[str], os_name: str, target: str, qt_version_or_spec: str) -> str: + """Choose a default architecture, if one can be determined""" + if arch is not None and arch != "": + return arch + if os_name == "linux" and target == "desktop": + try: + if Version(qt_version_or_spec) >= Version("6.7.0"): + return "linux_gcc_64" + else: + return "gcc_64" + except ValueError: + return "gcc_64" + elif os_name == "linux_arm64" and target == "desktop": + return "linux_gcc_arm64" + elif os_name == "mac" and target == "desktop": + return "clang_64" + elif os_name == "mac" and target == "ios": + return "ios" + elif target == "android": + try: + if Version(qt_version_or_spec) >= Version("5.14.0"): + return "android" + except ValueError: + pass + elif os_name == "windows_arm64" and target == "desktop": + return "windows_msvc2022_arm64" + raise CliInputError("Please supply a target architecture.", should_show_help=True) + + def _check_mirror(self, mirror): + if mirror is None: + pass + elif mirror.startswith("http://") or mirror.startswith("https://") or mirror.startswith("ftp://"): + pass + else: + return False + return True + + @staticmethod + def _determine_qt_version( + qt_version_or_spec: str, host: str, target: str, arch: str, base_url: str = Settings.baseurl + ) -> Version: + def choose_highest(x: Optional[Version], y: Optional[Version]) -> Optional[Version]: + if x and y: + return max(x, y) + return x or y + + def opt_version_for_spec(ext: str, _spec: SimpleSpec) -> Optional[Version]: + try: + meta = MetadataFactory(ArchiveId("qt", host, target), spec=_spec, base_url=base_url) + return meta.fetch_latest_version(ext) + except AqtException: + return None + + try: + return Version(qt_version_or_spec) + except ValueError: + pass + try: + spec = SimpleSpec(qt_version_or_spec) + except ValueError as e: + raise CliInputError(f"Invalid version or SimpleSpec: '{qt_version_or_spec}'\n" + SimpleSpec.usage()) from e + else: + version: Optional[Version] = None + for ext in QtRepoProperty.possible_extensions_for_arch(arch): + version = choose_highest(version, opt_version_for_spec(ext, spec)) + if not version: + raise CliInputError( + f"No versions of Qt exist for spec={spec} with host={host}, target={target}, arch={arch}" + ) + getLogger("aqt.installer").info(f"Resolved spec '{qt_version_or_spec}' to {version}") + return version + + @staticmethod + def choose_archive_dest(archive_dest: Optional[str], keep: bool, temp_dir: str) -> Path: + """ + Choose archive download destination, based on context. + + There are three potential behaviors here: + 1. By default, return a temp directory that will be removed on program exit. + 2. If the user has asked to keep archives, but has not specified a destination, + we return Settings.archive_download_location ("." by default). + 3. If the user has asked to keep archives and specified a destination, + we create the destination dir if it doesn't exist, and return that directory. + """ + if not archive_dest: + return Path(Settings.archive_download_location if keep else temp_dir) + dest = Path(archive_dest) + dest.mkdir(parents=True, exist_ok=True) + return dest + + def run_install_qt(self, args: InstallArgParser): + """Run install subcommand""" + start_time = time.perf_counter() + self.show_aqt_version() + target: str = args.target + os_name: str = args.host + effective_os_name: str = Cli._get_effective_os_name(os_name) + qt_version_or_spec: str = getattr(args, "qt_version", getattr(args, "qt_version_spec", "")) + arch: str = self._set_arch(args.arch, os_name, target, qt_version_or_spec) + keep: bool = args.keep or Settings.always_keep_archives + archive_dest: Optional[str] = args.archive_dest + dry_run: bool = args.dry_run + output_dir = args.outputdir + if output_dir is None: + base_dir = os.getcwd() + else: + base_dir = output_dir + if args.timeout is not None: + timeout = (args.timeout, args.timeout) + else: + timeout = (Settings.connection_timeout, Settings.response_timeout) + modules = args.modules + sevenzip = self._set_sevenzip(args.external) + if args.base is not None: + if not self._check_mirror(args.base): + raise CliInputError( + "The `--base` option requires a url where the path `online/qtsdkrepository` exists.", + should_show_help=True, + ) + base = args.base + else: + base = Settings.baseurl + if hasattr(args, "qt_version_spec"): + qt_version: str = str(Cli._determine_qt_version(args.qt_version_spec, os_name, target, arch, base_url=base)) + else: + qt_version = args.qt_version + Cli._validate_version_str(qt_version) + + if qt_version != qt_version_or_spec: + arch = self._set_arch(args.arch, os_name, target, qt_version) + + if hasattr(args, "use_official_installer") and args.use_official_installer is not None: + + if len(args.use_official_installer) not in [0, 2]: + raise CliInputError( + "When providing arguments to --use-official-installer, exactly 2 arguments are required: " + "--use-official-installer email password" + ) + + self.logger.info("Using official Qt installer") + + commercial_args = InstallArgParser() + + # Core parameters required by install-qt-official + commercial_args.target = args.target + commercial_args.arch = self._set_arch( + args.arch, args.host, args.target, getattr(args, "qt_version", getattr(args, "qt_version_spec", "")) + ) + + commercial_args.version = qt_version + + email = None + password = None + if len(args.use_official_installer) == 2: + email, password = args.use_official_installer + self.logger.info("Using credentials provided with --use-official-installer") + + # Optional parameters + commercial_args.email = email or getattr(args, "email", None) + commercial_args.pw = password or getattr(args, "pw", None) + commercial_args.outputdir = args.outputdir + commercial_args.modules = args.modules + commercial_args.base = getattr(args, "base", None) + commercial_args.dry_run = getattr(args, "dry_run", False) + commercial_args.override = None + + ignored_options = [] + if getattr(args, "noarchives", False): + ignored_options.append("--noarchives") + if getattr(args, "autodesktop", False): + ignored_options.append("--autodesktop") + if getattr(args, "archives", None): + ignored_options.append("--archives") + if getattr(args, "timeout", False): + ignored_options.append("--timeout") + if getattr(args, "keep", False): + ignored_options.append("--keep") + if getattr(args, "archive_dest", False): + ignored_options.append("--archive_dest") + + if ignored_options: + self.logger.warning("Options ignored because you requested the official installer:") + self.logger.warning(", ".join(ignored_options)) + + return self.run_install_qt_commercial(commercial_args, print_version=False) + + archives = args.archives + if args.noarchives: + if modules is None: + raise CliInputError("When `--noarchives` is set, the `--modules` option is mandatory.") + if archives is not None: + raise CliInputError("Options `--archives` and `--noarchives` are mutually exclusive.") + else: + if modules is not None and archives is not None: + archives.extend(modules) + nopatch = args.noarchives or (archives is not None and "qtbase" not in archives) # type: bool + should_autoinstall: bool = args.autodesktop + _version = Version(qt_version) + base_path = Path(base_dir) + + # Determine if 'all' extra modules should be included + all_extra = True if modules is not None and "all" in modules else False + + expect_desktop_archdir, autodesk_arch = self._get_autodesktop_dir_and_arch( + should_autoinstall, os_name, target, base_path, _version, arch + ) + + # Main installation + qt_archives: QtArchives = retry_on_bad_connection( + lambda base_url: QtArchives( + os_name, + target, + qt_version, + arch, + base=base_url, + subarchives=archives, + modules=modules, + all_extra=all_extra, + is_include_base_package=not args.noarchives, + timeout=timeout, + ), + base, + ) + + target_config = qt_archives.get_target_config() + target_config.os_name = effective_os_name + + with TemporaryDirectory() as temp_dir: + _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir) + run_installer(qt_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest, dry_run=dry_run) + + if dry_run: + return + + if not nopatch: + Updater.update(target_config, base_path, expect_desktop_archdir) + + # If autodesktop is enabled and we need a desktop installation, do it first + if should_autoinstall and autodesk_arch is not None: + is_wasm = arch.startswith("wasm") + is_msvc = "msvc" in arch + is_win_desktop_msvc_arm64 = ( + effective_os_name == "windows" + and target == "desktop" + and is_msvc + and arch.endswith(("arm64", "arm64_cross_compiled")) + ) + if is_win_desktop_msvc_arm64: + qt_type = "MSVC Arm64" + elif is_wasm: + qt_type = "Qt6-WASM" + else: + qt_type = target + + # Create new args for desktop installation + self.logger.info("") + self.logger.info( + f"Autodesktop will now install {effective_os_name} desktop " + f"{qt_version} {autodesk_arch} as required by {qt_type}" + ) + + desktop_args = args + args.autodesktop = False + args.host = effective_os_name + args.target = "desktop" + args.arch = autodesk_arch + + # Run desktop installation first + self.run_install_qt(desktop_args) + + else: + self.logger.info("Finished installation") + self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time)) + + def _run_src_doc_examples(self, flavor, args, cmd_name: Optional[str] = None): + self.show_aqt_version() + if getattr(args, "target", None) is not None: + self._warn_on_deprecated_parameter("target", args.target) + target = "desktop" # The only valid target for src/doc/examples is "desktop" + os_name = args.host + output_dir = args.outputdir + if output_dir is None: + base_dir = os.getcwd() + else: + base_dir = output_dir + keep: bool = args.keep or Settings.always_keep_archives + archive_dest: Optional[str] = args.archive_dest + if args.base is not None: + base = args.base + else: + base = Settings.baseurl + if hasattr(args, "qt_version_spec"): + qt_version = str(Cli._determine_qt_version(args.qt_version_spec, os_name, target, arch="", base_url=base)) + else: + qt_version = args.qt_version + Cli._validate_version_str(qt_version) + # Override target/os for recent Qt + if Version(qt_version) in SimpleSpec(">=6.7.0"): + target = "qt" + os_name = "all_os" + if args.timeout is not None: + timeout = (args.timeout, args.timeout) + else: + timeout = (Settings.connection_timeout, Settings.response_timeout) + sevenzip = self._set_sevenzip(args.external) + modules = getattr(args, "modules", None) # `--modules` is invalid for `install-src` + archives = args.archives + all_extra = True if modules is not None and "all" in modules else False + + srcdocexamples_archives: SrcDocExamplesArchives = retry_on_bad_connection( + lambda base_url: SrcDocExamplesArchives( + flavor, + os_name, + target, + qt_version, + base=base_url, + subarchives=archives, + modules=modules, + all_extra=all_extra, + timeout=timeout, + ), + base, + ) + with TemporaryDirectory() as temp_dir: + _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir) + run_installer( + srcdocexamples_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest, dry_run=args.dry_run + ) + self.logger.info("Finished installation") + + def run_install_src(self, args): + """Run src subcommand""" + if not hasattr(args, "qt_version"): + base = args.base if hasattr(args, "base") else Settings.baseurl + args.qt_version = str( + Cli._determine_qt_version(args.qt_version_spec, args.host, args.target, arch="", base_url=base) + ) + if args.kde and args.qt_version != "5.15.2": + raise CliInputError("KDE patch: unsupported version!!") + start_time = time.perf_counter() + self._run_src_doc_examples("src", args) + if args.kde: + if args.outputdir is None: + target_dir = os.path.join(os.getcwd(), args.qt_version, "Src") + else: + target_dir = os.path.join(args.outputdir, args.qt_version, "Src") + Updater.patch_kde(target_dir) + self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time)) + + def run_install_example(self, args): + """Run example subcommand""" + start_time = time.perf_counter() + self._run_src_doc_examples("examples", args, cmd_name="example") + self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time)) + + def run_install_doc(self, args): + """Run doc subcommand""" + start_time = time.perf_counter() + self._run_src_doc_examples("doc", args) + self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time)) + + def run_install_tool(self, args: InstallToolArgParser): + """Run tool subcommand""" + start_time = time.perf_counter() + self.show_aqt_version() + tool_name = args.tool_name # such as tools_openssl_x64 + os_name = args.host # windows, linux and mac + target = args.target # desktop, android and ios + output_dir = args.outputdir + if output_dir is None: + base_dir = os.getcwd() + else: + base_dir = output_dir + sevenzip = self._set_sevenzip(args.external) + version = getattr(args, "version", None) + if version is not None: + Cli._validate_version_str(version, allow_minus=True) + keep: bool = args.keep or Settings.always_keep_archives + archive_dest: Optional[str] = args.archive_dest + if args.base is not None: + base = args.base + else: + base = Settings.baseurl + if args.timeout is not None: + timeout = (args.timeout, args.timeout) + else: + timeout = (Settings.connection_timeout, Settings.response_timeout) + if args.tool_variant is None: + archive_id = ArchiveId("tools", os_name, target) + meta = MetadataFactory(archive_id, base_url=base, is_latest_version=True, tool_name=tool_name) + try: + archs: List[str] = cast(list, meta.getList()) + except ArchiveDownloadError as e: + msg = f"Failed to locate XML data for the tool '{tool_name}'." + raise ArchiveListError(msg, suggested_action=suggested_follow_up(meta)) from e + + else: + archs = [args.tool_variant] + + for arch in archs: + tool_archives: ToolArchives = retry_on_bad_connection( + lambda base_url: ToolArchives( + os_name=os_name, + tool_name=tool_name, + target=target, + base=base_url, + version_str=version, + arch=arch, + timeout=timeout, + ), + base, + ) + with TemporaryDirectory() as temp_dir: + _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir) + run_installer(tool_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest, dry_run=args.dry_run) + self.logger.info("Finished installation") + self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time)) + + def run_list_qt(self, args: ListArgumentParser): + """Print versions of Qt, extensions, modules, architectures""" + + if hasattr(args, "use_official_installer") and args.use_official_installer is not None: + + if len(args.use_official_installer) not in [0, 2]: + raise CliInputError( + "When providing arguments to --use-official-installer, exactly 2 arguments are required: " + "--use-official-installer email password" + ) + + self.logger.info("Using official Qt installer for search") + + commercial_search_args = ListArgumentParser() + + email = None + password = None + if len(args.use_official_installer) == 2: + email, password = args.use_official_installer + self.logger.info("Using credentials provided with --use-official-installer") + + commercial_search_args.email = email or getattr(args, "email", None) + commercial_search_args.pw = password or getattr(args, "pw", None) + + target_str = "" + version_str = "" + if hasattr(args, "target") and args.target is not None: + target_str = args.target + if hasattr(args, "arch") and args.arch is not None: + try: + version = Version(args.arch) + version_str = f"{version.major}{version.minor}{version.patch}" + except Exception as e: + self.logger.warning(f"{e}. Ignoring 'arch' value") + + commercial_search_args.search_terms = [rf"^.*{re.escape(version_str)}\.{re.escape(target_str)}.*$"] + + ignored_options = [] + if getattr(args, "extensions", False): + ignored_options.append("--extensions") + if getattr(args, "extension", False): + ignored_options.append("--extension") + if getattr(args, "modules", None): + ignored_options.append("--modules") + if getattr(args, "long_modules", False): + ignored_options.append("--long_modules") + if getattr(args, "spec", False): + ignored_options.append("--spec") + if getattr(args, "archives", False): + ignored_options.append("--archives") + if getattr(args, "latest-version", False): + ignored_options.append("--latest-version") + + if ignored_options: + self.logger.warning("Options ignored because you requested the official installer:") + self.logger.warning(", ".join(ignored_options)) + + return self.run_list_qt_commercial(commercial_search_args, print_version=False) + + if args.extensions: + self._warn_on_deprecated_parameter("extensions", args.extensions) + self.logger.warning( + "The '--extensions' flag will always return an empty list, " + "because there are no useful arguments for the '--extension' flag." + ) + print("") + return + if args.extension: + self._warn_on_deprecated_parameter("extension", args.extension) + self.logger.warning("The '--extension' flag will be ignored.") + + if not args.target: + print(" ".join(ArchiveId.TARGETS_FOR_HOST[args.host])) + return + if args.target not in ArchiveId.TARGETS_FOR_HOST[args.host]: + raise CliInputError("'{0.target}' is not a valid target for host '{0.host}'".format(args)) + if args.modules: + assert len(args.modules) == 2, "broken argument parser for list-qt" + modules_query = MetadataFactory.ModulesQuery(args.modules[0], args.modules[1]) + modules_ver, is_long = args.modules[0], False + elif args.long_modules: + assert args.long_modules and len(args.long_modules) == 2, "broken argument parser for list-qt" + modules_query = MetadataFactory.ModulesQuery(args.long_modules[0], args.long_modules[1]) + modules_ver, is_long = args.long_modules[0], True + else: + modules_ver, modules_query, is_long = None, None, False + + for version_str in (modules_ver, args.arch, args.archives[0] if args.archives else None): + Cli._validate_version_str(version_str, allow_latest=True, allow_empty=True) + + spec = None + try: + if args.spec is not None: + spec = SimpleSpec(args.spec) + except ValueError as e: + raise CliInputError(f"Invalid version specification: '{args.spec}'.\n" + SimpleSpec.usage()) from e + + meta = MetadataFactory( + archive_id=ArchiveId("qt", args.host, args.target), + spec=spec, + is_latest_version=args.latest_version, + modules_query=modules_query, + is_long_listing=is_long, + architectures_ver=args.arch, + archives_query=args.archives, + ) + show_list(meta) + + def run_list_tool(self, args: ListToolArgumentParser): + """Print tools""" + + if not args.target: + print(" ".join(ArchiveId.TARGETS_FOR_HOST[args.host])) + return + if args.target not in ArchiveId.TARGETS_FOR_HOST[args.host]: + raise CliInputError("'{0.target}' is not a valid target for host '{0.host}'".format(args)) + + meta = MetadataFactory( + archive_id=ArchiveId("tools", args.host, args.target), + tool_name=args.tool_name, + is_long_listing=args.long, + ) + show_list(meta) + + def run_list_src_doc_examples(self, args: ListArgumentParser, cmd_type: str): + target = "desktop" + version = Cli._determine_qt_version(args.qt_version_spec, args.host, target, arch="") + if version >= Version("6.7.0"): + target = "qt" + host = "all_os" + else: + host = args.host + is_fetch_modules: bool = getattr(args, "modules", False) + meta = MetadataFactory( + archive_id=ArchiveId("qt", host, target), + src_doc_examples_query=MetadataFactory.SrcDocExamplesQuery(cmd_type, version, is_fetch_modules), + ) + show_list(meta) + + def run_install_qt_commercial(self, args: InstallArgParser, print_version: Optional[bool] = True) -> None: + """Execute commercial Qt installation""" + if print_version: + self.show_aqt_version() + + try: + if args.override: + username, password, override_args = extract_auth(args.override) + commercial_installer = CommercialInstaller( + target="", # Empty string as placeholder + arch="", + version=None, + logger=self.logger, + base_url=args.base if args.base is not None else Settings.baseurl, + override=override_args, + no_unattended=not Settings.qt_installer_unattended, + username=username or args.email, + password=password or args.pw, + dry_run=args.dry_run, + ) + else: + if not all([args.target, args.arch, args.version]): + raise CliInputError("target, arch, and version are required") + + commercial_installer = CommercialInstaller( + target=args.target, + arch=args.arch, + version=args.version, + username=args.email, + password=args.pw, + output_dir=args.outputdir, + logger=self.logger, + base_url=args.base if args.base is not None else Settings.baseurl, + no_unattended=not Settings.qt_installer_unattended, + modules=args.modules, + dry_run=args.dry_run, + ) + + commercial_installer.install() + Settings.qt_installer_cleanup() + except Exception as e: + self.logger.error(f"Error installing official installer: {str(e)}") + finally: + self.logger.info("Done") + + def show_help(self, args=None): + """Display help message""" + self.parser.print_help() + + def _format_aqt_version(self) -> str: + py_version = platform.python_version() + py_impl = platform.python_implementation() + py_build = platform.python_compiler() + return f"aqtinstall(aqt) v{aqt.__version__} on Python {py_version} [{py_impl} {py_build}]" + + def show_aqt_version(self, args: Optional[list[str]] = None) -> None: + """Display version information""" + self.logger.info(self._format_aqt_version()) + + def _set_install_qt_parser(self, install_qt_parser): + install_qt_parser.set_defaults(func=self.run_install_qt) + install_qt_parser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + install_qt_parser.add_argument( + "target", + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + help="Target SDK", + ) + install_qt_parser.add_argument( + "qt_version_spec", + metavar="(VERSION | SPECIFICATION)", + help='Qt version in the format of "5.X.Y" or SimpleSpec like "5.X" or "<6.X"', + ) + install_qt_parser.add_argument( + "arch", + nargs="?", + help="\ntarget linux/desktop: linux_gcc_64, gcc_64, wasm_32" + "\ntarget mac/desktop: clang_64, wasm_32" + "\ntarget mac/ios: ios" + "\nwindows/desktop: win64_msvc2022_64" + "\n win64_msvc2019_64, win32_msvc2019" + "\n win64_msvc2017_64, win32_msvc2017" + "\n win64_msvc2015_64, win32_msvc2015" + "\n win64_mingw81, win32_mingw81" + "\n win64_mingw73, win32_mingw73" + "\n win32_mingw53" + "\n wasm_32" + "\nwindows/winrt: win64_msvc2019_winrt_x64, win64_msvc2019_winrt_x86" + "\n win64_msvc2017_winrt_x64, win64_msvc2017_winrt_x86" + "\n win64_msvc2019_winrt_armv7" + "\n win64_msvc2017_winrt_armv7" + "\nandroid: Qt 5.14: android (optional)" + "\n Qt 5.13 or below: android_x86_64, android_arm64_v8a" + "\n android_x86, android_armv7" + "\nall_os/wasm: wasm_singlethread, wasm_multithread", + ) + self._set_common_options(install_qt_parser) + self._set_module_options(install_qt_parser) + self._set_archive_options(install_qt_parser) + install_qt_parser.add_argument( + "--noarchives", + action="store_true", + help="No base packages; allow mod amendment with --modules option.", + ) + install_qt_parser.add_argument( + "--autodesktop", + action="store_true", + help="For Qt6 android, ios, wasm, and msvc_arm64 installations, an additional desktop Qt installation is " + "required. When enabled, this option installs the required desktop version automatically. " + "It has no effect when the desktop installation is not required.", + ) + install_qt_parser.add_argument( + "--use-official-installer", + nargs="*", + default=None, + metavar=("EMAIL", "PASSWORD"), + help="Use the official Qt installer for installation instead of the aqt downloader. " + "Can be used without arguments or with email and password: --use-official-installer email password. " + "This redirects to install-qt-official. " + "Arguments not compatible with the official installer will be ignored.", + ) + + def _set_install_tool_parser(self, install_tool_parser): + install_tool_parser.set_defaults(func=self.run_install_tool) + install_tool_parser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + install_tool_parser.add_argument( + "target", + default=None, + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + help="Target SDK.", + ) + install_tool_parser.add_argument("tool_name", help="Name of tool such as tools_ifw, tools_mingw") + + tool_variant_opts = {"nargs": "?", "default": None} + install_tool_parser.add_argument( + "tool_variant", + **tool_variant_opts, + help="Name of tool variant, such as qt.tools.ifw.41. " + "Please use 'aqt list-tool' to list acceptable values for this parameter.", + ) + self._set_common_options(install_tool_parser) + + def _set_install_qt_commercial_parser(self, install_qt_commercial_parser: argparse.ArgumentParser) -> None: + install_qt_commercial_parser.set_defaults(func=self.run_install_qt_commercial) + + # Create mutually exclusive group for override vs standard parameters + exclusive_group = install_qt_commercial_parser.add_mutually_exclusive_group() + exclusive_group.add_argument( + "--override", + nargs=argparse.REMAINDER, + help="Will ignore all other parameters and use everything after this parameter as " + "input for the official Qt installer", + ) + + # Make standard arguments optional when override is used by adding a custom action + class ConditionalRequiredAction(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None) -> None: + if not hasattr(namespace, "override") or not namespace.override: + setattr(namespace, self.dest, values) + + install_qt_commercial_parser.add_argument( + "target", + nargs="?", + choices=["desktop", "android", "ios"], + help="Target platform", + action=ConditionalRequiredAction, + ) + install_qt_commercial_parser.add_argument( + "arch", nargs="?", help="Target architecture", action=ConditionalRequiredAction + ) + install_qt_commercial_parser.add_argument("version", nargs="?", help="Qt version", action=ConditionalRequiredAction) + + install_qt_commercial_parser.add_argument( + "--email", + help="Qt account email", + ) + install_qt_commercial_parser.add_argument( + "--pw", + help="Qt account password", + ) + install_qt_commercial_parser.add_argument( + "-m", + "--modules", + nargs="*", + help="Add modules", + ) + self._set_common_options(install_qt_commercial_parser) + + def _set_list_qt_commercial_parser(self, list_qt_commercial_parser: argparse.ArgumentParser) -> None: + """Configure parser for list-qt-official command with flexible argument handling.""" + list_qt_commercial_parser.set_defaults(func=self.run_list_qt_commercial) + + list_qt_commercial_parser.add_argument( + "--email", + help="Qt account email", + ) + list_qt_commercial_parser.add_argument( + "--pw", + help="Qt account password", + ) + + # Capture all remaining arguments as search terms + list_qt_commercial_parser.add_argument( + "search_terms", + nargs="*", # Zero or more arguments + help="Search terms (all non-option arguments are treated as search terms)", + ) + + def run_list_qt_commercial(self, args: ListArgumentParser, print_version: Optional[bool] = True) -> None: + """Execute Qt commercial package listing.""" + if print_version: + self.show_aqt_version() + + # Create temporary directory for installer + temp_dir = Settings.qt_installer_temp_path + temp_path = Path(temp_dir) + if not temp_path.exists(): + temp_path.mkdir(parents=True, exist_ok=True) + else: + Settings.qt_installer_cleanup() + + # Get installer based on OS + installer_filename = get_qt_installer_name() + installer_path = temp_path / installer_filename + + try: + # Download installer + self.logger.info(f"Downloading Qt installer to {installer_path}") + timeout = (Settings.connection_timeout, Settings.response_timeout) + download_installer(Settings.baseurl, installer_filename, installer_path, timeout) + installer_path = prepare_installer(installer_path, get_os_name()) + + # Build command + cmd = [str(installer_path), "--accept-licenses", "--accept-obligations", "--confirm-command"] + + if args.email and args.pw: + cmd.extend(["--email", args.email, "--pw", args.pw]) + + cmd.append("search") + + # Add all search terms if present + if args.search_terms: + cmd.extend(args.search_terms) + + # Run search + output = safely_run_save_output(cmd, Settings.qt_installer_timeout) + + if output.stdout: + self.logger.info(output.stdout) + if output.stderr: + for line in output.stderr.splitlines(): + self.logger.warning(line) + + except Exception as e: + self.logger.error(f"Failed to list Qt official packages: {e}") + finally: + Settings.qt_installer_cleanup() + + def _warn_on_deprecated_command(self, old_name: str, new_name: str) -> None: + self.logger.warning( + f"The command '{old_name}' is deprecated and marked for removal in a future version of aqt.\n" + f"In the future, please use the command '{new_name}' instead." + ) + + def _warn_on_deprecated_parameter(self, parameter_name: str, value: str): + self.logger.warning( + f"The parameter '{parameter_name}' with value '{value}' is deprecated and marked for " + f"removal in a future version of aqt.\n" + f"In the future, please omit this parameter." + ) + + def _make_all_parsers(self, subparsers: argparse._SubParsersAction) -> None: + """Creates all command parsers and adds them to the subparsers""" + + def make_parser_it(cmd: str, desc: str, set_parser_cmd, formatter_class): + kwargs = {"formatter_class": formatter_class} if formatter_class else {} + p = subparsers.add_parser(cmd, description=desc, **kwargs) + set_parser_cmd(p) + + def make_parser_sde(cmd: str, desc: str, action, is_add_kde: bool, is_add_modules: bool = True): + parser = subparsers.add_parser(cmd, description=desc) + parser.set_defaults(func=action) + self._set_common_arguments(parser, is_target_deprecated=True) + self._set_common_options(parser) + if is_add_modules: + self._set_module_options(parser) + self._set_archive_options(parser) + if is_add_kde: + parser.add_argument("--kde", action="store_true", help="patching with KDE patch kit.") + + def make_parser_list_sde(cmd: str, desc: str, cmd_type: str): + parser = subparsers.add_parser(cmd, description=desc) + parser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + parser.add_argument( + "qt_version_spec", + metavar="(VERSION | SPECIFICATION)", + help='Qt version in the format of "5.X.Y" or SimpleSpec like "5.X" or "<6.X"', + ) + parser.set_defaults(func=lambda args: self.run_list_src_doc_examples(args, cmd_type)) + + if cmd_type != "src": + parser.add_argument("-m", "--modules", action="store_true", help="Print list of available modules") + + # Create install command parsers + make_parser_it("install-qt", "Install Qt.", self._set_install_qt_parser, argparse.RawTextHelpFormatter) + make_parser_it("install-tool", "Install tools.", self._set_install_tool_parser, None) + make_parser_it( + "install-qt-official", + "Install Qt with official installer.", + self._set_install_qt_commercial_parser, + argparse.RawTextHelpFormatter, + ) + make_parser_it( + "list-qt-official", + "Search packages using Qt official installer.", + self._set_list_qt_commercial_parser, + argparse.RawTextHelpFormatter, + ) + make_parser_sde("install-doc", "Install documentation.", self.run_install_doc, False) + make_parser_sde("install-example", "Install examples.", self.run_install_example, False) + make_parser_sde("install-src", "Install source.", self.run_install_src, True, is_add_modules=False) + + # Create list command parsers + self._make_list_qt_parser(subparsers) + self._make_list_tool_parser(subparsers) + make_parser_list_sde("list-doc", "List documentation archives available (use with install-doc)", "doc") + make_parser_list_sde("list-example", "List example archives available (use with install-example)", "examples") + make_parser_list_sde("list-src", "List source archives available (use with install-src)", "src") + + self._make_common_parsers(subparsers) + + def _make_list_qt_parser(self, subparsers: argparse._SubParsersAction): + """Creates a subparser that works with the MetadataFactory, and adds it to the `subparsers` parameter""" + list_parser: ListArgumentParser = subparsers.add_parser( + "list-qt", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Examples:\n" + "$ aqt list-qt mac # print all targets for Mac OS\n" + "$ aqt list-qt mac desktop # print all versions of Qt 5\n" + '$ aqt list-qt mac desktop --spec "5.9" # print all versions of Qt 5.9\n' + '$ aqt list-qt mac desktop --spec "5.9" --latest-version # print latest Qt 5.9\n' + "$ aqt list-qt mac desktop --modules 5.12.0 clang_64 # print modules for 5.12.0\n" + "$ aqt list-qt mac desktop --spec 5.9 --modules latest clang_64 # print modules for latest 5.9\n" + "$ aqt list-qt mac desktop --arch 5.9.9 # print architectures for " + "5.9.9/mac/desktop\n" + "$ aqt list-qt mac desktop --arch latest # print architectures for the " + "latest Qt 5\n" + "$ aqt list-qt mac desktop --archives 5.9.0 clang_64 # list archives in base Qt " + "installation\n" + "$ aqt list-qt mac desktop --archives 5.14.0 clang_64 debug_info # list archives in debug_info " + "module\n" + "$ aqt list-qt all_os wasm --arch 6.8.1 # print architectures for Qt WASM " + "6.8.1\n", + ) + list_parser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + list_parser.add_argument( + "target", + nargs="?", + default=None, + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + help="Target SDK. When omitted, this prints all the targets available for a host OS.", + ) + list_parser.add_argument( + "--extension", + choices=ArchiveId.ALL_EXTENSIONS, + help="Deprecated since aqt v3.1.0. Use of this flag will emit a warning, but will otherwise be ignored.", + ) + list_parser.add_argument( + "--spec", + type=str, + metavar="SPECIFICATION", + help="Filter output so that only versions that match the specification are printed. " + 'IE: `aqt list-qt windows desktop --spec "5.12"` prints all versions beginning with 5.12', + ) + list_parser.add_argument( + "--use-official-installer", + nargs="*", + default=None, + metavar=("EMAIL", "PASSWORD"), + help="Use the official Qt installer for research instead of the aqt researcher. " + "Can be used without arguments or with email and password: --use-official-installer email password. " + "This redirects to list-qt-official. " + "Arguments not compatible with the official installer will be ignored.", + ) + output_modifier_exclusive_group = list_parser.add_mutually_exclusive_group() + output_modifier_exclusive_group.add_argument( + "--modules", + type=str, + nargs=2, + metavar=("(VERSION | latest)", "ARCHITECTURE"), + help='First arg: Qt version in the format of "5.X.Y", or the keyword "latest". ' + 'Second arg: an architecture, which may be printed with the "--arch" flag. ' + "When set, this prints all the modules available for either Qt 5.X.Y or the latest version of Qt.", + ) + output_modifier_exclusive_group.add_argument( + "--long-modules", + type=str, + nargs=2, + metavar=("(VERSION | latest)", "ARCHITECTURE"), + help='First arg: Qt version in the format of "5.X.Y", or the keyword "latest". ' + 'Second arg: an architecture, which may be printed with the "--arch" flag. ' + "When set, this prints a table that describes all the modules available " + "for either Qt 5.X.Y or the latest version of Qt.", + ) + output_modifier_exclusive_group.add_argument( + "--extensions", + type=str, + metavar="(VERSION | latest)", + help="Deprecated since v3.1.0. Prints a list of valid arguments for the '--extension' flag. " + "Since the '--extension' flag is now deprecated, this will always print an empty list.", + ) + output_modifier_exclusive_group.add_argument( + "--arch", + type=str, + metavar="(VERSION | latest)", + help='Qt version in the format of "5.X.Y", or the keyword "latest". ' + "When set, this prints all architectures available for either Qt 5.X.Y or the latest version of Qt.", + ) + output_modifier_exclusive_group.add_argument( + "--latest-version", + action="store_true", + help="print only the newest version available", + ) + output_modifier_exclusive_group.add_argument( + "--archives", + type=str, + nargs="+", + help="print the archives available for Qt base or modules. " + "If two arguments are provided, the first two arguments must be 'VERSION | latest' and " + "'ARCHITECTURE', and this command will print all archives associated with the base Qt package. " + "If more than two arguments are provided, the remaining arguments will be interpreted as modules, " + "and this command will print all archives associated with those modules. " + "At least two arguments are required.", + ) + list_parser.set_defaults(func=self.run_list_qt) + + def _make_list_tool_parser(self, subparsers: argparse._SubParsersAction): + """Creates a subparser that works with the MetadataFactory, and adds it to the `subparsers` parameter""" + list_parser: ListArgumentParser = subparsers.add_parser( + "list-tool", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Examples:\n" + "$ aqt list-tool mac desktop # print all tools for mac desktop\n" + "$ aqt list-tool mac desktop tools_ifw # print all tool variant names for QtIFW\n" + "$ aqt list-tool mac desktop ifw # print all tool variant names for QtIFW\n" + "$ aqt list-tool mac desktop tools_ifw --long # print tool variant names with metadata for QtIFW\n" + "$ aqt list-tool mac desktop ifw --long # print tool variant names with metadata for QtIFW\n", + ) + list_parser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + list_parser.add_argument( + "target", + nargs="?", + default=None, + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + help="Target SDK. When omitted, this prints all the targets available for a host OS.", + ) + list_parser.add_argument( + "tool_name", + nargs="?", + default=None, + help='Name of a tool, ie "tools_mingw" or "tools_ifw". ' + "When omitted, this prints all the tool names available for a host OS/target SDK combination. " + "When present, this prints all the tool variant names available for this tool. ", + ) + list_parser.add_argument( + "-l", + "--long", + action="store_true", + help="Long display: shows a table of metadata associated with each tool variant. " + "On narrow terminals, it displays tool variant names, versions, and release dates. " + "On terminals wider than 95 characters, it also displays descriptions of each tool.", + ) + list_parser.set_defaults(func=self.run_list_tool) + + def _make_common_parsers(self, subparsers: argparse._SubParsersAction) -> None: + help_parser = subparsers.add_parser("help") + help_parser.set_defaults(func=self.show_help) + version_parser = subparsers.add_parser("version") + version_parser.set_defaults(func=self.show_aqt_version) + + def _set_common_options(self, subparser: argparse.ArgumentParser) -> None: + subparser.add_argument( + "-O", + "--outputdir", + nargs="?", + help="Target output directory(default current directory)", + ) + subparser.add_argument( + "-b", + "--base", + nargs="?", + help="Specify mirror base url such as http://mirrors.ocf.berkeley.edu/qt/, " "where 'online' folder exist.", + ) + subparser.add_argument( + "--timeout", + nargs="?", + type=float, + help="Specify connection timeout for download site.(default: 5 sec)", + ) + subparser.add_argument("-E", "--external", nargs="?", help="Specify external 7zip command path.") + subparser.add_argument("--internal", action="store_true", help="Use internal extractor.") + subparser.add_argument( + "-k", + "--keep", + action="store_true", + help="Keep downloaded archive when specified, otherwise remove after install", + ) + subparser.add_argument( + "-d", + "--archive-dest", + type=str, + default=None, + help="Set the destination path for downloaded archives (temp directory by default).", + ) + subparser.add_argument( + "--dry-run", + action="store_true", + help="Print what would be downloaded and installed without actually doing it", + ) + subparser.add_argument( + "--UNSAFE-ignore-hash", + action="store_true", + help="UNSAFE: Skip hash verification of downloaded files. Use at your own risk.", + ) + + def _set_module_options(self, subparser): + subparser.add_argument("-m", "--modules", nargs="*", help="Specify extra modules to install") + + def _set_archive_options(self, subparser): + subparser.add_argument( + "--archives", + nargs="*", + help="Specify subset of archives to install. Affects the base module and the debug_info module. " + "(Default: all archives).", + ) + + def _set_common_arguments(self, subparser, *, is_target_deprecated: bool = False): + """ + install-src/doc/example commands do not require a "target" argument anymore, as of 11/22/2021 + """ + subparser.add_argument( + "host", + choices=["linux", "linux_arm64", "mac", "windows", "windows_arm64", "all_os"], + help="host os name", + ) + if is_target_deprecated: + subparser.add_argument( + "target", + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + nargs="?", + help="Ignored. This parameter is deprecated and marked for removal in a future release. " + "It is present here for backwards compatibility.", + ) + else: + subparser.add_argument( + "target", + choices=["desktop", "winrt", "android", "ios", "wasm", "qt"], + help="target sdk", + ) + subparser.add_argument( + "qt_version_spec", + metavar="(VERSION | SPECIFICATION)", + help='Qt version in the format of "5.X.Y" or SimpleSpec like "5.X" or "<6.X"', + ) + + def _setup_settings(self, args=None): + # setup logging + setup_logging() + self.logger = getLogger("aqt.main") + # setup settings + if args is not None and args.config is not None: + Settings.load_settings(args.config) + else: + config = os.getenv("AQT_CONFIG", None) + if config is not None and os.path.exists(config): + Settings.load_settings(config) + self.logger.debug("Load configuration from {}".format(config)) + else: + Settings.load_settings() + + # Set ignore_hash to True if --UNSAFE-ignore-hash flag was passed + if args is not None and hasattr(args, "UNSAFE_ignore_hash") and args.UNSAFE_ignore_hash: + self.logger.warning( + "************************************************************************************************" + ) + self.logger.warning( + "Hash verification is disabled. This is UNSAFE and may allow malicious files to be downloaded." + ) + self.logger.warning( + "If your install mirror hosts malicious files, you won't be able to know. Use at your own risk." + ) + self.logger.warning( + "************************************************************************************************" + ) + Settings.set_ignore_hash_for_session(True) + + @staticmethod + def _validate_version_str( + version_str: Optional[str], + *, + allow_latest: bool = False, + allow_empty: bool = False, + allow_minus: bool = False, + ) -> None: + """ + Raise CliInputError if the version is not an acceptable Version. + + :param version_str: The version string to check. + :param allow_latest: If true, the string "latest" is acceptable. + :param allow_empty: If true, the empty string is acceptable. + :param allow_minus: If true, everything after the first '-' in the version will be ignored. + This allows acceptance of versions like "1.2.3-0-202101020304" + """ + if allow_latest and version_str == "latest": + return + if not version_str: + if allow_empty: + return + else: + raise CliInputError("Invalid empty version! Please use the form '5.X.Y'.") + try: + if "-" in version_str and allow_minus: + version_str = version_str[: version_str.find("-")] + Version(version_str) + except ValueError as e: + raise CliInputError(f"Invalid version: '{version_str}'! Please use the form '5.X.Y'.") from e + + def _get_autodesktop_dir_and_arch( + self, + should_autoinstall: bool, + host: str, + target: str, + base_path: Path, + version: Version, + arch: str, + ) -> Tuple[Optional[str], Optional[str]]: + """Returns expected_desktop_arch_dir, desktop_arch_to_install""" + is_wasm = arch.startswith("wasm") + is_msvc = "msvc" in arch + is_win_desktop_msvc_arm64 = ( + host == "windows" and target == "desktop" and is_msvc and arch.endswith(("arm64", "arm64_cross_compiled")) + ) + if version < Version("6.0.0") or ( + target not in ["ios", "android", "wasm"] and not is_wasm and not is_win_desktop_msvc_arm64 + ): + # We only need to worry about the desktop directory for Qt6 mobile or wasm installs. + return None, None + + # For WASM installations on all_os, we need to choose a default desktop host + host = Cli._get_effective_os_name(host) + + installed_desktop_arch_dir = QtRepoProperty.find_installed_desktop_qt_dir(host, base_path, version, is_msvc=is_msvc) + if installed_desktop_arch_dir: + # An acceptable desktop Qt is already installed, so don't do anything. + self.logger.info(f"Found installed {host}-desktop Qt at {installed_desktop_arch_dir}") + return installed_desktop_arch_dir.name, None + + try: + default_desktop_arch = MetadataFactory(ArchiveId("qt", host, "desktop")).fetch_default_desktop_arch( + version, is_msvc + ) + except ValueError as e: + if "Target 'desktop' is invalid" in str(e): + # Special case for all_os host which doesn't support desktop target + return None, None + raise + + desktop_arch_dir = QtRepoProperty.get_arch_dir_name(host, default_desktop_arch, version) + expected_desktop_arch_path = base_path / dir_for_version(version) / desktop_arch_dir + + if is_win_desktop_msvc_arm64: + qt_type = "MSVC Arm64" + elif is_wasm: + qt_type = "Qt6-WASM" + else: + qt_type = target + + if should_autoinstall: + # No desktop Qt is installed, but the user has requested installation. Find out what to install. + self.logger.info(f"You are installing the {qt_type} version of Qt") + return expected_desktop_arch_path.name, default_desktop_arch + else: + self.logger.warning( + f"You are installing the {qt_type} version of Qt, which requires that the desktop version of Qt " + f"is also installed. You can install it with the following command:\n" + f" `aqt install-qt {host} desktop {version} {default_desktop_arch}`" + ) + return expected_desktop_arch_path.name, None + + @staticmethod + def _get_effective_os_name(host: str) -> str: + if host != "all_os": + return host + elif sys.platform.startswith("linux"): + return "linux" + elif sys.platform == "darwin": + return "mac" + else: + return "windows" + + +def is_64bit() -> bool: + """check if running platform is 64bit python.""" + return sys.maxsize > 1 << 32 + + +def run_installer( + archives: List[QtPackage], + base_dir: str, + sevenzip: Optional[str], + keep: bool, + archive_dest: Path, + dry_run: bool = False, +): + + if dry_run: + logger = getLogger("aqt.installer") + logger.info("DRY RUN: Would download and install the following:") + for arc in archives: + line_parts = [f" - {arc.name}: {arc.archive_path}"] + + if hasattr(arc, "package_desc") and arc.package_desc: + size_match = re.search(r"Size: ([^,]+)", arc.package_desc) + if size_match: + line_parts.append(f" ({size_match.group(1)})") + + if arc.archive_install_path and arc.archive_install_path.strip(): + line_parts.append(f" -> {arc.archive_install_path}") + + logger.info("".join(line_parts)) + + logger.info(f"Total packages: {len(archives)}") + return + + queue = multiprocessing.Manager().Queue(-1) + listener = MyQueueListener(queue) + listener.start() + # + tasks = [] + for arc in archives: + tasks.append((arc, base_dir, sevenzip, queue, archive_dest, Settings.configfile, keep)) + ctx = multiprocessing.get_context("spawn") + if is_64bit(): + pool = ctx.Pool(Settings.concurrency, init_worker_sh, (), 4) + else: + pool = ctx.Pool(Settings.concurrency, init_worker_sh, (), 1) + + def close_worker_pool_on_exception(exception: BaseException): + logger = getLogger("aqt.installer") + logger.warning(f"Caught {exception.__class__.__name__}, terminating installer workers") + pool.terminate() + pool.join() + + try: + pool.starmap(installer, tasks) + pool.close() + pool.join() + except PermissionError as e: # subclass of OSError + close_worker_pool_on_exception(e) + raise DiskAccessNotPermitted( + f"Failed to write to base directory at {base_dir}", + suggested_action=[ + "Check that the destination is writable and does not already contain files owned by another user." + ], + ) from e + except OSError as e: + close_worker_pool_on_exception(e) + if e.errno == errno.ENOSPC: + raise OutOfDiskSpace( + "Insufficient disk space to complete installation.", + suggested_action=[ + "Check available disk space.", + "Check size requirements for installation.", + ], + ) from e + else: + raise + except KeyboardInterrupt as e: + close_worker_pool_on_exception(e) + raise CliKeyboardInterrupt("Installer halted by keyboard interrupt.") from e + except MemoryError as e: + close_worker_pool_on_exception(e) + alt_extractor_msg = ( + "Please try using the '--external' flag to specify an alternate 7z extraction tool " + "(see https://aqtinstall.readthedocs.io/en/latest/cli.html#cmdoption-list-tool-external)" + ) + if Settings.concurrency > 1: + docs_url = "https://aqtinstall.readthedocs.io/en/stable/configuration.html#configuration" + raise OutOfMemory( + "Out of memory when downloading and extracting archives in parallel.", + suggested_action=[ + f"Please reduce your 'concurrency' setting (see {docs_url})", + alt_extractor_msg, + ], + ) from e + raise OutOfMemory( + "Out of memory when downloading and extracting archives.", + suggested_action=["Please free up more memory.", alt_extractor_msg], + ) + except Exception as e: + close_worker_pool_on_exception(e) + raise e from e + finally: + # all done, close logging service for sub-processes + listener.enqueue_sentinel() + listener.stop() + + +def init_worker_sh() -> None: + """Initialize worker signal handling""" + signal.signal(signal.SIGINT, signal.SIG_IGN) + + +def installer( + qt_package: QtPackage, + base_dir: str, + command: Optional[str], + queue: multiprocessing.Queue, + archive_dest: Path, + settings_ini: str, + keep: bool, +) -> None: + """ + Installer function to download archive files and extract it. + It is called through multiprocessing.Pool() + """ + name = qt_package.name + base_url = qt_package.base_url + archive: Path = archive_dest / qt_package.archive + base_dir = posixpath.join(base_dir, qt_package.archive_install_path) + start_time = time.perf_counter() + Settings.load_settings(file=settings_ini) + # setup queue logger + setup_logging() + qh = QueueHandler(queue) + logger = getLogger() + for handler in logger.handlers: + handler.close() + logger.removeHandler(handler) + logger.addHandler(qh) + # + timeout = (Settings.connection_timeout, Settings.response_timeout) + hash = get_hash(qt_package.archive_path, Settings.hash_algorithm, timeout) if not Settings.ignore_hash else None + + def download_bin(_base_url): + url = posixpath.join(_base_url, qt_package.archive_path) + logger.debug("Download URL: {}".format(url)) + return downloadBinaryFile(url, archive, Settings.hash_algorithm, hash, timeout) + + retry_on_errors( + action=lambda: retry_on_bad_connection(download_bin, base_url), + acceptable_errors=(ArchiveChecksumError,), + num_retries=Settings.max_retries_on_checksum_error, + name=f"Downloading {name}", + ) + gc.collect() + + if tarfile.is_tarfile(archive): + with tarfile.open(archive) as tar_archive: + if hasattr(tarfile, "data_filter"): + tar_archive.extractall(filter="tar", path=base_dir) + else: + # remove this when the minimum Python version is 3.12 + logger.warning("Extracting may be unsafe; consider updating Python to 3.11.4 or greater") + tar_archive.extractall(path=base_dir) + elif zipfile.is_zipfile(archive): + with zipfile.ZipFile(archive) as zip_archive: + zip_archive.extractall(path=base_dir) + elif command is None: + with py7zr.SevenZipFile(archive, "r") as szf: + szf.extractall(path=base_dir) + else: + command_args = [command, "x", "-aoa", "-bd", "-y", "-o{}".format(base_dir), str(archive)] + try: + proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True) + logger.debug(proc.stdout) + except subprocess.CalledProcessError as cpe: + msg = "\n".join(filter(None, [f"Extraction error: {cpe.returncode}", cpe.stdout, cpe.stderr])) + raise ArchiveExtractionError(msg) from cpe + if not keep: + os.unlink(archive) + logger.info("Finished installation of {} in {:.8f}".format(archive.name, time.perf_counter() - start_time)) + gc.collect() + qh.flush() + qh.close() + logger.removeHandler(qh) diff --git a/python/py313/Lib/site-packages/aqt/logging.ini b/python/py313/Lib/site-packages/aqt/logging.ini new file mode 100644 index 0000000000000000000000000000000000000000..b3c688a9129a98c99fcd9a54e4b44c21103a170d --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/logging.ini @@ -0,0 +1,78 @@ +[loggers] +keys=root,aqt + +[logger_root] +level=NOTSET +handlers=console + +[logger_aqt] +level=DEBUG +handlers=console,file +propagate=0 +qualname=aqt + +[logger_aqt_main] +level=INFO +propagate=1 +qualname=aqt.main + +[logger_aqt_archives] +level=INFO +propagate=1 +qualname=aqt.archives + +[logger_aqt_generate_combos] +level=INFO +propagate=1 +qualname=aqt.generate_combos + +[logger_aqt_helper] +level=INFO +propagate=1 +qualname=aqt.helper + +[logger_aqt_installer] +level=INFO +handlers=NOTSET +propagate=0 +qualname=aqt.installer + +[logger_aqt_metadata] +level=INFO +propagate=1 +qualname=aqt.metadata + +[logger_aqt_updater] +level=INFO +propagate=1 +qualname=aqt.updater + +[formatters] +keys=verbose,simple,brief + +[formatter_verbose] +format=%(asctime)s - %(name)s - %(levelname)s - %(module)s %(thread)d %(message)s +class=logging.Formatter + +[formatter_simple] +format=%(asctime)s - %(name)s - %(levelname)s - %(message)s +class=logging.Formatter + +[formatter_brief] +format=%(levelname)-8s: %(message)s +class=logging.Formatter + +[handlers] +keys=console,file + +[handler_console] +level=INFO +class=logging.StreamHandler +formatter=brief +args=(sys.stderr,) + +[handler_file] +level=DEBUG +class=logging.FileHandler +formatter=verbose +args=('aqtinstall.log', 'a') diff --git a/python/py313/Lib/site-packages/aqt/metadata.py b/python/py313/Lib/site-packages/aqt/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..30df5d4c2a7b1d3c98972407d79a8554eea2ddbc --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/metadata.py @@ -0,0 +1,1235 @@ +#!/usr/bin/env python +# +# Copyright (C) 2021 David Dalcino +# +# 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. +import itertools +import operator +import os +import posixpath +import re +import secrets as random +import shutil +from abc import ABC, abstractmethod +from functools import reduce +from logging import getLogger +from pathlib import Path +from typing import Callable, Dict, Generator, Iterable, Iterator, List, NamedTuple, Optional, Set, Tuple, Union, cast +from urllib.parse import ParseResult, urlparse +from xml.etree.ElementTree import Element + +import bs4 +from semantic_version import SimpleSpec as SemanticSimpleSpec +from semantic_version import Version as SemanticVersion +from texttable import Texttable + +from aqt.exceptions import ( + ArchiveConnectionError, + ArchiveDownloadError, + ArchiveListError, + ChecksumDownloadFailure, + CliInputError, + EmptyMetadata, +) +from aqt.helper import Settings, get_hash, getUrl, xml_to_modules + + +class SimpleSpec(SemanticSimpleSpec): + pass + + @staticmethod + def usage() -> str: + return ( + "See documentation at: " + "https://python-semanticversion.readthedocs.io/en/latest/reference.html#semantic_version.SimpleSpec\n" + "Examples:\n" + '* "*": matches everything\n' + '* "5": matches every version with major=5\n' + '* "5.6": matches every version beginning with 5.6\n' + '* "5.*.3": matches versions with major=5 and patch=3' + ) + + +class Version(SemanticVersion): + """Override semantic_version.Version class + to accept Qt versions and tools versions + If the version ends in `-preview`, the version is treated as a preview release. + """ + + def __init__( + self, + version_string=None, + major=None, + minor=None, + patch=None, + prerelease=None, + build=None, + partial=False, + ) -> None: + if version_string is None: + super(Version, self).__init__( + version_string=None, + major=major, + minor=minor, + patch=patch, + prerelease=prerelease, + build=build, + partial=partial, + ) + return + # test qt versions + match = re.match(r"^(\d+)\.(\d+)(\.(\d+)|-preview)$", version_string) + if not match: + # bad input + raise ValueError("Invalid version string: '{}'".format(version_string)) + major, minor, end, patch = match.groups() + is_preview = end == "-preview" + super(Version, self).__init__( + major=int(major), + minor=int(minor), + patch=int(patch) if patch else 0, + prerelease=("preview",) if is_preview else None, + ) + + def __str__(self): + if self.prerelease: + return "{}.{}-preview".format(self.major, self.minor) + return super(Version, self).__str__() + + @classmethod + def permissive(cls, version_string: str): + """Converts a version string with dots (5.X.Y, etc) into a semantic version. + If the version omits either the patch or minor versions, they will be filled in with zeros, + and the remaining version string becomes part of the prerelease component. + If the version cannot be converted to a Version, a ValueError is raised. + + This is intended to be used on Version tags in an Updates.xml file. + + '1.33.1-202102101246' => Version('1.33.1-202102101246') + '1.33-202102101246' => Version('1.33.0-202102101246') # tools_conan + '2020-05-19-1' => Version('2020.0.0-05-19-1') # tools_vcredist + """ + + match = re.match(r"^(\d+)(\.(\d+)(\.(\d+))?)?(-(.+))?$", version_string) + if not match: + raise ValueError("Invalid version string: '{}'".format(version_string)) + major, dot_minor, minor, dot_patch, patch, hyphen_build, build = match.groups() + return cls( + major=int(major), + minor=int(minor) if minor else 0, + patch=int(patch) if patch else 0, + build=(build,) if build else None, + ) + + +class Versions: + def __init__( + self, + versions: Union[None, Version, Iterable[Tuple[int, Iterable[Version]]]], + ): + if versions is None: + self.versions: List[List[Version]] = list() + elif isinstance(versions, Version): + self.versions = [[versions]] + else: + self.versions = [list(versions_iterator) for _, versions_iterator in versions] + + def __str__(self) -> str: + return str(self.versions) + + def __format__(self, format_spec) -> str: + if format_spec == "": + return "\n".join(" ".join(str(version) for version in minor_list) for minor_list in self.versions) + elif format_spec == "s": + return str(self.versions) + else: + raise TypeError("Unsupported format.") + + def __bool__(self): + return len(self.versions) > 0 and len(self.versions[0]) > 0 + + def latest(self) -> Optional[Version]: + if not self: + return None + return self.versions[-1][-1] + + def __iter__(self) -> Generator[List[Version], None, None]: + for item in self.versions: + yield item + + def flattened(self) -> List[Version]: + """Return a flattened list of all versions""" + return [version for row in self for version in row] + + +def get_semantic_version(qt_ver: str, is_preview: bool) -> Optional[Version]: + """Converts a Qt version string (596, 512, 5132, etc) into a semantic version. + This makes a lot of assumptions based on established patterns: + If is_preview is True, the number is interpreted as ver[0].ver[1:], with no patch. + If the version is 3 digits, then major, minor, and patch each get 1 digit. + If the version is 4 or more digits, then major gets 1 digit, minor gets 2 digits + and patch gets all the rest. + As of May 2021, the version strings at https://download.qt.io/online/qtsdkrepository + conform to this pattern; they are not guaranteed to do so in the future. + As of December 2024, it can handle version strings like 6_7_3 as well. + """ + if not qt_ver: + return None + + # Handle versions with underscores (new format) + if "_" in qt_ver: + parts = qt_ver.split("_") + if not (2 <= len(parts) <= 3): + return None + + try: + version_parts = [int(p) for p in parts] + except ValueError: + return None + + major, minor = version_parts[:2] + patch = version_parts[2] if len(version_parts) > 2 else 0 + + if is_preview: + minor_patch_combined = int(f"{minor}{patch}") if patch > 0 else minor + return Version( + major=major, + minor=minor_patch_combined, + patch=0, + prerelease=("preview",), + ) + + return Version( + major=major, + minor=minor, + patch=patch, + ) + + # Handle traditional format (continuous digits) + if not qt_ver.isdigit(): + return None + + if is_preview: + return Version( + major=int(qt_ver[0]), + minor=int(qt_ver[1:]), + patch=0, + prerelease=("preview",), + ) + elif len(qt_ver) >= 4: + return Version(major=int(qt_ver[0]), minor=int(qt_ver[1:3]), patch=int(qt_ver[3:])) + elif len(qt_ver) == 3: + return Version(major=int(qt_ver[0]), minor=int(qt_ver[1]), patch=int(qt_ver[2])) + elif len(qt_ver) == 2: + return Version(major=int(qt_ver[0]), minor=int(qt_ver[1]), patch=0) + + raise ValueError("Invalid version string '{}'".format(qt_ver)) + + +class ArchiveId: + CATEGORIES = ("tools", "qt") + HOSTS = ("windows", "windows_arm64", "mac", "linux", "linux_arm64", "all_os") + TARGETS_FOR_HOST = { + "windows": ["android", "desktop", "winrt"], + "windows_arm64": ["desktop"], + "mac": ["android", "desktop", "ios"], + "linux": ["android", "desktop"], + "linux_arm64": ["desktop"], + "all_os": ["wasm", "qt", "android"], + } + EXTENSIONS_REQUIRED_ANDROID_QT6 = {"x86_64", "x86", "armv7", "arm64_v8a"} + ALL_EXTENSIONS = { + "", + "wasm", + "src_doc_examples", + *EXTENSIONS_REQUIRED_ANDROID_QT6, + } + + def __init__(self, category: str, host: str, target: str): + if category not in ArchiveId.CATEGORIES: + raise ValueError("Category '{}' is invalid".format(category)) + if host not in ArchiveId.HOSTS: + raise ValueError("Host '{}' is invalid".format(host)) + if target not in ArchiveId.TARGETS_FOR_HOST[host]: + raise ValueError("Target '{}' is invalid".format(target)) + self.category: str = category + self.host: str = host + self.target: str = target + + def is_preview(self) -> bool: + return False + + def is_qt(self) -> bool: + return self.category == "qt" + + def is_tools(self) -> bool: + return self.category == "tools" + + def to_os_arch(self) -> str: + if self.host == "all_os": + return "all_os" + return "{os}{arch}".format( + os=self.host, + arch=( + "_x86" + if self.host == "windows" + else ("" if self.host in ("linux_arm64", "all_os", "windows_arm64") else "_x64") + ), + ) + + def to_extension_folder(self, module, version, arch) -> str: + extarch = arch + if self.host == "windows": + extarch = arch.replace("win64_", "", 1) + elif self.host == "linux": + extarch = "x86_64" + elif self.host == "linux_arm64": + extarch = "arm64" + + return "online/qtsdkrepository/{osarch}/extensions/{ext}/{ver}/{extarch}/".format( + osarch=self.to_os_arch(), + ext=module, + ver=version, + extarch=extarch, + ) + + def to_extension_url(self) -> str: + return "online/qtsdkrepository/{osarch}/extensions/".format( + osarch=self.to_os_arch(), + ) + + def to_url(self) -> str: + return "online/qtsdkrepository/{osarch}/{target}/".format( + osarch=self.to_os_arch(), + target=self.target, + ) + + def to_folder(self, version: Version, qt_version_no_dots: str, extension: Optional[str] = None) -> str: + if version >= Version("6.8.0"): + if self.target == "wasm": + # Qt 6.8+ WASM uses a split folder structure + folder = f"qt{version.major}_{qt_version_no_dots}" + if extension: + folder = f"{folder}/{folder}_{extension}" + return folder + elif not ((self.host == "all_os") and (self.target == "qt")): + # Non-WASM, non-all_os/qt case + return "{category}{major}_{ver}/{category}{major}_{ver}{ext}".format( + category=self.category, + major=qt_version_no_dots[0], + ver=qt_version_no_dots, + ext="_" + extension if extension else "", + ) + else: + # traditional structure, still used by sde. + return "{category}{major}_{ver}{ext}".format( + category=self.category, + major=qt_version_no_dots[0], + ver=qt_version_no_dots, + ext="_" + extension if extension else "", + ) + elif version >= Version("6.5.0") and self.target == "wasm": + # Qt 6.5-6.7 WASM uses direct wasm_[single|multi]thread folder + if extension: + return f"qt{version.major}_{qt_version_no_dots}_{extension}" + return f"qt{version.major}_{qt_version_no_dots}" + + # Pre-6.8 structure for non-WASM or pre-6.5 structure + return "{category}{major}_{ver}{ext}".format( + category=self.category, + major=qt_version_no_dots[0], + ver=qt_version_no_dots, + ext="_" + extension if extension else "", + ) + + def all_extensions(self, version: Version) -> List[str]: + if self.target == "desktop" and QtRepoProperty.is_in_wasm_range(self.host, version): + return ["", "wasm"] + elif self.target == "desktop" and QtRepoProperty.is_in_wasm_range_special_65x_66x(self.host, version): + return ["", "wasm_singlethread", "wasm_multithread"] + elif self.target == "wasm" and QtRepoProperty.is_in_wasm_threaded_range(version): + return ["wasm_singlethread", "wasm_multithread"] + elif self.target == "android" and version >= Version("6.0.0"): + return list(ArchiveId.EXTENSIONS_REQUIRED_ANDROID_QT6) + else: + return [""] + + def __str__(self) -> str: + return "{cat}/{host}/{target}".format( + cat=self.category, + host=self.host, + target=self.target, + ) + + +class TableMetadata(ABC): + """A data class that holds tool or module details. Can be pretty-printed as a table.""" + + def __init__(self, table_data: Dict[str, Dict[str, str]]): + self.table_data: Dict[str, Dict[str, str]] = table_data + self.format_field_for_tty("Description") + + def format_field_for_tty(self, field: str): + for key in self.table_data.keys(): + if field in self.table_data[key] and self.table_data[key][field]: + self.table_data[key][field] = self.table_data[key][field].replace("
", "\n") + + std_keys_to_headings = { + "ReleaseDate": "Release Date", + "DisplayName": "Display Name", + "CompressedSize": "Download Size", + "UncompressedSize": "Installed Size", + } + + @classmethod + def map_key_to_heading(cls, key: str) -> str: + return TableMetadata.std_keys_to_headings.get(key, key) + + @property + @abstractmethod + def short_heading_keys(self) -> Iterable[str]: ... + + @property + @abstractmethod + def long_heading_keys(self) -> Iterable[str]: ... + + @property + @abstractmethod + def name_heading(self) -> str: ... + + def __format__(self, format_spec: str) -> str: + short = False + if format_spec == "{:s}": + return str(self) + if format_spec == "": + max_width: int = 0 + elif format_spec == "{:T}": + short = True + max_width = 0 + else: + match = re.match(r"\{?:?(\d+)t\}?", format_spec) + if match: + g = match.groups() + max_width = int(g[0]) + else: + raise ValueError("Wrong format {}".format(format_spec)) + table = Texttable(max_width=max_width) + table.set_deco(Texttable.HEADER) + + heading_keys = self.short_heading_keys if short else self.long_heading_keys + heading = [self.name_heading, *[self.map_key_to_heading(key) for key in heading_keys]] + table.header(heading) + table.add_rows(self._rows(heading_keys), header=False) + return cast(str, table.draw()) + + def __bool__(self): + return bool(self.table_data) + + def _rows(self, keys: Iterable[str]) -> List[List[str]]: + return [[name, *[content[key] for key in keys]] for name, content in sorted(self.table_data.items())] + + +class ToolData(TableMetadata): + """A data class hold tool details.""" + + @property + def short_heading_keys(self) -> Iterable[str]: + return "Version", "ReleaseDate" + + @property + def long_heading_keys(self) -> Iterable[str]: + return "Version", "ReleaseDate", "DisplayName", "Description" + + @property + def name_heading(self) -> str: + return "Tool Variant Name" + + +class ModuleData(TableMetadata): + """A data class hold module details.""" + + @property + def short_heading_keys(self) -> Iterable[str]: + return ("DisplayName",) + + @property + def long_heading_keys(self) -> Iterable[str]: + return "DisplayName", "ReleaseDate", "CompressedSize", "UncompressedSize" + + @property + def name_heading(self) -> str: + return "Module Name" + + +class QtRepoProperty: + """ + Describes properties of the Qt repository at https://download.qt.io/online/qtsdkrepository. + Intended to help decouple the logic of aqt from specific properties of the Qt repository. + """ + + @staticmethod + def dir_for_version(ver: Version) -> str: + return "5.9" if ver == Version("5.9.0") else f"{ver.major}.{ver.minor}.{ver.patch}" + + @staticmethod + def get_arch_dir_name(host: str, arch: str, version: Version) -> str: + """ + Determines the architecture directory name based on host, architecture and version. + Special handling is done for mingw, MSVC and various platform-specific cases. + """ + if arch.startswith("win64_mingw"): + return arch[6:] + "_64" + elif arch.startswith("win64_llvm"): + return "llvm-" + arch[11:] + "_64" + elif arch.startswith("win32_mingw"): + return arch[6:] + "_32" + elif arch.startswith("win"): + m = re.match(r"win\d{2}_(?Pmsvc\d{4})_(?Pwinrt_x\d{2})", arch) + if m: + return f"{m.group('winrt')}_{m.group('msvc')}" + elif arch.endswith("_cross_compiled"): + return arch[6:-15] + else: + return arch[6:] + elif host == "mac" and arch == "clang_64": + return QtRepoProperty.default_mac_desktop_arch_dir(version) + elif host == "linux" and arch in ("gcc_64", "linux_gcc_64"): + return "gcc_64" + elif host == "linux_arm64" and arch == "linux_gcc_arm64": + return "gcc_arm64" + else: + return arch + + @staticmethod + def default_linux_desktop_arch_dir() -> Tuple[str, str]: + return ("gcc_64", "gcc_arm64") + + @staticmethod + def default_win_msvc_desktop_arch_dir(_version: Version) -> str: + if _version >= Version("6.8.0"): + return "msvc2022_64" + else: + return "msvc2019_64" + + @staticmethod + def default_mac_desktop_arch_dir(version: Version) -> str: + return "macos" if version in SimpleSpec(">=6.1.2") else "clang_64" + + @staticmethod + def extension_for_arch(architecture: str, is_version_ge_6: bool) -> str: + if architecture == "wasm_32": + return "wasm" + elif architecture == "wasm_singlethread": + return "wasm_singlethread" + elif architecture == "wasm_multithread": + return "wasm_multithread" + elif architecture.startswith("android_") and is_version_ge_6: + ext = architecture[len("android_") :] + if ext in ArchiveId.EXTENSIONS_REQUIRED_ANDROID_QT6: + return ext + return "" + + @staticmethod + def possible_extensions_for_arch(arch: str) -> List[str]: + """Assumes no knowledge of the Qt version""" + + # ext_ge_6: the extension if the version is greater than or equal to 6.0.0 + # ext_lt_6: the extension if the version is less than 6.0.0 + ext_lt_6, ext_ge_6 = [QtRepoProperty.extension_for_arch(arch, is_ge_6) for is_ge_6 in (False, True)] + if ext_lt_6 == ext_ge_6: + return [ext_lt_6] + return [ext_lt_6, ext_ge_6] + + # Architecture, as reported in Updates.xml + MINGW_ARCH_PATTERN = re.compile(r"^win(?P\d+)_mingw(?P\d+)?$") + # Directory that corresponds to an architecture + MINGW_DIR_PATTERN = re.compile(r"^mingw(?P\d+)?_(?P\d+)$") + + @staticmethod + def select_default_mingw(mingw_arches: List[str], is_dir: bool) -> Optional[str]: + """ + Selects a default architecture from a non-empty list of mingw architectures, matching the pattern + MetadataFactory.MINGW_ARCH_PATTERN. Meant to be called on a list of installed mingw architectures, + or a list of architectures available for installation. + """ + + ArchBitsVer = Tuple[str, int, Optional[int]] + pattern = QtRepoProperty.MINGW_DIR_PATTERN if is_dir else QtRepoProperty.MINGW_ARCH_PATTERN + + def mingw_arch_with_bits_and_version(arch: str) -> Optional[ArchBitsVer]: + match = pattern.match(arch) + if not match: + return None + bits = int(match.group("bits")) + ver = None if not match.group("version") else int(match.group("version")) + return arch, bits, ver + + def select_superior_arch(lhs: ArchBitsVer, rhs: ArchBitsVer) -> ArchBitsVer: + _, l_bits, l_ver = lhs + _, r_bits, r_ver = rhs + if l_bits != r_bits: + return lhs if l_bits > r_bits else rhs + elif r_ver is None: + return lhs + elif l_ver is None: + return rhs + return lhs if l_ver > r_ver else rhs + + candidates: List[ArchBitsVer] = list(filter(None, map(mingw_arch_with_bits_and_version, mingw_arches))) + if len(candidates) == 0: + return None + default_arch, _, _ = reduce(select_superior_arch, candidates) + return default_arch + + @staticmethod + def find_installed_desktop_qt_dir(host: str, base_path: Path, version: Version, is_msvc: bool = False) -> Optional[Path]: + """ + Locates the default installed desktop qt directory, somewhere in base_path. + """ + installed_qt_version_dir = base_path / QtRepoProperty.dir_for_version(version) + if host == "mac": + arch_path = installed_qt_version_dir / QtRepoProperty.default_mac_desktop_arch_dir(version) + return arch_path if (arch_path / "bin/qmake").is_file() else None + elif host == "linux": + for arch_dir in QtRepoProperty.default_linux_desktop_arch_dir(): + arch_path = installed_qt_version_dir / arch_dir + if (arch_path / "bin/qmake").is_file(): + return arch_path + return None + elif host == "windows" and is_msvc: + arch_path = installed_qt_version_dir / QtRepoProperty.default_win_msvc_desktop_arch_dir(version) + return arch_path if (arch_path / "bin/qmake.exe").is_file() else None + + def contains_qmake_exe(arch_path: Path) -> bool: + return (arch_path / "bin/qmake.exe").is_file() + + paths = [d for d in installed_qt_version_dir.glob("mingw*")] + directories = list(filter(contains_qmake_exe, paths)) + arch_dirs = [d.name for d in directories] + selected_dir = QtRepoProperty.select_default_mingw(arch_dirs, is_dir=True) + return installed_qt_version_dir / selected_dir if selected_dir else None + + @staticmethod + def is_in_wasm_range(host: str, version: Version) -> bool: + return ( + version in SimpleSpec(">=6.2.0,<6.5.0") + or (host == "linux" and version in SimpleSpec(">=5.13,<6")) + or version in SimpleSpec(">=5.13.1,<6") + ) + + @staticmethod + def is_in_wasm_range_special_65x_66x(host: str, version: Version) -> bool: + return version in SimpleSpec(">=6.5.0,<6.7.0") + + @staticmethod + def is_in_wasm_threaded_range(version: Version) -> bool: + return version in SimpleSpec(">=6.5.0") + + @staticmethod + def known_extensions(version: Version) -> List[str]: + if version >= Version("6.8.0"): + return ["qtpdf", "qtwebengine"] + return [] + + @staticmethod + def sde_ext(version: Version) -> str: + if version >= Version("6.8.0"): + if os.linesep == "\r\n": + return "windows_line_endings_src" + else: + return "unix_line_endings_src" + else: + return "src_doc_examples" + + +class MetadataFactory: + """Retrieve metadata of Qt variations, versions, and descriptions from Qt site.""" + + Metadata = Union[List[str], Versions, ToolData, ModuleData] + Action = Callable[[], Metadata] + SrcDocExamplesQuery = NamedTuple( + "SrcDocExamplesQuery", [("cmd_type", str), ("version", Version), ("is_modules_query", bool)] + ) + ModulesQuery = NamedTuple("ModulesQuery", [("version_str", str), ("arch", str)]) + + def __init__( + self, + archive_id: ArchiveId, + *, + base_url: Optional[str] = None, + spec: Optional[SimpleSpec] = None, + is_latest_version: bool = False, + modules_query: Optional[ModulesQuery] = None, + architectures_ver: Optional[str] = None, + archives_query: Optional[List[str]] = None, + src_doc_examples_query: Optional[SrcDocExamplesQuery] = None, + tool_name: Optional[str] = None, + is_long_listing: bool = False, + ): + """ + Construct MetadataFactory. + + :param spec: When set, the MetadataFactory will filter out all versions of + Qt that don't fit this SimpleSpec. + :param is_latest_version: When True, the MetadataFactory will find all versions of Qt + matching filters, and only print the most recent version + :param modules_query: [Version of Qt, architecture] for which to list modules + :param architectures_ver: Version of Qt for which to list architectures + :param archives_query: [Qt_Version, architecture, *module_names]: used to print list of archives + :param tool_name: Name of a tool, without architecture, ie "tools_qtcreator" or "tools_ifw" + :param is_long_listing: If true, long listing is used for tools output + """ + self.logger = getLogger("aqt.metadata") + self.archive_id = archive_id + self.spec = spec + self.base_url = base_url or Settings.baseurl + + if archive_id.is_tools(): + if tool_name is not None: + if not tool_name.startswith("tools_") and tool_name != "sdktool": + _tool_name = f"tools_{tool_name}" + else: + _tool_name = tool_name + if is_long_listing: + self.request_type = "tool long listing" + self._action: MetadataFactory.Action = lambda: self.fetch_tool_long_listing(_tool_name) + else: + self.request_type = "tool variant names" + self._action = lambda: self.fetch_tool_modules(_tool_name) + else: + self.request_type = "tools" + self._action = self.fetch_tools + elif is_latest_version: + self.request_type = "latest version" + self._action = lambda: Versions(self.fetch_latest_version(ext="")) + elif modules_query is not None: + version, arch = modules_query.version_str, modules_query.arch + if is_long_listing: + self.request_type = "long modules" + self._action = lambda: self.fetch_long_modules(self._to_version(version, arch), arch) + else: + self.request_type = "modules" + self._action = lambda: self.fetch_modules(self._to_version(version, arch), arch) + elif architectures_ver is not None: + ver_str: str = architectures_ver + self.request_type = "architectures" + self._action = lambda: self.fetch_arches(self._to_version(ver_str, None)) + elif archives_query: + if len(archives_query) < 2: + raise CliInputError("The '--archives' flag requires a 'QT_VERSION' and an 'ARCHITECTURE' parameter.") + self.request_type = "archives for modules" if len(archives_query) > 2 else "archives for qt" + version, arch, modules = archives_query[0], archives_query[1], archives_query[2:] + self._action = lambda: self.fetch_archives(self._to_version(version, arch), arch, modules) + elif src_doc_examples_query is not None: + q: MetadataFactory.SrcDocExamplesQuery = src_doc_examples_query + if q.is_modules_query: + self.request_type = f"modules for {q.cmd_type}" + self._action = lambda: self.fetch_modules_sde(q.cmd_type, q.version) + else: + self.request_type = f"archives for {q.cmd_type}" + self._action = lambda: self.fetch_archives_sde(q.cmd_type, q.version) + else: + self.request_type = "versions" + self._action = self.fetch_versions + + def getList(self) -> Metadata: + return self._action() + + def fetch_arches(self, version: Version) -> List[str]: + arches = [] + qt_ver_str = self._get_qt_version_str(version) + for extension in self.archive_id.all_extensions(version): + modules: Dict[str, Dict[str, str]] = {} + folder = self.archive_id.to_folder(version, qt_ver_str, extension) + try: + modules = self._fetch_module_metadata(folder) + except ArchiveDownloadError as e: + if extension == "": + raise + else: + self.logger.debug(e) + self.logger.debug( + f"Failed to retrieve arches list with extension `{extension}`. " + f"Please check that this extension exists for this version of Qt: " + f"if not, code changes will be necessary." + ) + # It's ok to swallow this error: we will still print the other available architectures that aqt can + # install successfully. This is to prevent future errors such as those reported in #643 + + for name in modules.keys(): + ver, arch = name.split(".")[-2:] + if ver == qt_ver_str: + arches.append(arch) + + return arches + + def fetch_versions(self, extension: str = "") -> Versions: + def match_any_ext(ver: Version) -> bool: + return ( + self.archive_id.host == "all_os" + and self.archive_id.target in ArchiveId.TARGETS_FOR_HOST["all_os"] + and ver in SimpleSpec("6.7.*") + ) + + def filter_by(ver: Version, ext: str) -> bool: + return (self.spec is None or ver in self.spec) and (ext == extension or match_any_ext(ver)) + + versions_extensions = self.get_versions_extensions( + self.fetch_http(self.archive_id.to_url(), False), self.archive_id.category + ) + versions = sorted({ver for ver, ext in versions_extensions if ver is not None and filter_by(ver, ext)}) + grouped = cast(Iterable[Tuple[int, Iterable[Version]]], itertools.groupby(versions, lambda version: version.minor)) + + return Versions(grouped) + + def fetch_latest_version(self, ext: str) -> Optional[Version]: + return self.fetch_versions(ext).latest() + + def fetch_extensions(self) -> List[str]: + html_doc = self.fetch_http(self.archive_id.to_extension_url(), False) + return list(self.iterate_folders(html_doc, self.base_url)) + + def fetch_tools(self) -> List[str]: + html_doc = self.fetch_http(self.archive_id.to_url(), False) + return list(self.iterate_folders(html_doc, self.base_url, filter_category="tools")) + + def fetch_tool_modules(self, tool_name: str) -> List[str]: + tool_data = self._fetch_module_metadata(tool_name) + return list(tool_data.keys()) + + def fetch_tool_by_simple_spec(self, tool_name: str, simple_spec: SimpleSpec) -> Optional[Dict[str, str]]: + # Get data for all the tool modules + all_tools_data = self._fetch_module_metadata(tool_name) + return self.choose_highest_version_in_spec(all_tools_data, simple_spec) + + def fetch_tool_long_listing(self, tool_name: str) -> ToolData: + return ToolData(self._fetch_module_metadata(tool_name)) + + @staticmethod + def choose_highest_version_in_spec( + all_tools_data: Dict[str, Dict[str, str]], simple_spec: SimpleSpec + ) -> Optional[Dict[str, str]]: + # Get versions of all modules. Fail if version cannot be determined. + try: + tools_versions = [ + (name, tool_data, Version.permissive(tool_data["Version"])) for name, tool_data in all_tools_data.items() + ] + except ValueError: + return None + + # Remove items that don't conform to simple_spec + tools_versions = [tool_item for tool_item in tools_versions if tool_item[2] in simple_spec] + + try: + # Return the conforming item with the highest version. + # If there are multiple items with the same version, the result will not be predictable. + return max(tools_versions, key=operator.itemgetter(2))[1] + except ValueError: + # There were no tools that fit the simple_spec + return None + + def _to_version(self, qt_ver: str, arch: Optional[str]) -> Version: + """ + Turns a string in the form of `5.X.Y | latest` into a semantic version. + If the string does not fit either of these forms, CliInputError will be raised. + If qt_ver == latest, and no versions exist corresponding to the filters specified, + then CliInputError will be raised. + If qt_ver == latest, and an HTTP error occurs, requests.RequestException will be raised. + + :param qt_ver: Either the literal string `latest`, or a semantic version + with each part separated with dots. + """ + assert qt_ver + if qt_ver == "latest": + ext = QtRepoProperty.extension_for_arch(arch, True) if arch else "" + latest_version = self.fetch_latest_version(ext) + if not latest_version: + msg = "There is no latest version of Qt with the criteria '{}'".format(self.describe_filters()) + raise CliInputError(msg) + return latest_version + try: + version = Version(qt_ver) + except ValueError as e: + raise CliInputError(e) from e + return version + + def fetch_http(self, rest_of_url: str, is_check_hash: bool = True) -> str: + timeout = (Settings.connection_timeout, Settings.response_timeout) + expected_hash = get_hash(rest_of_url, Settings.hash_algorithm, timeout) if is_check_hash else None + base_urls = self.base_url, random.choice(Settings.fallbacks) + + err: BaseException = AssertionError("unraisable") + + for i, base_url in enumerate(base_urls): + try: + url = posixpath.join(base_url, rest_of_url) + return getUrl(url=url, timeout=timeout, expected_hash=expected_hash) + + except (ArchiveDownloadError, ArchiveConnectionError) as e: + err = e + if i < len(base_urls) - 1: + getLogger("aqt.metadata").debug( + f"Connection to '{base_url}' failed. Retrying with fallback '{base_urls[i + 1]}'." + ) + raise err from err + + def iterate_folders(self, html_doc: str, html_url: str, *, filter_category: str = "") -> Generator[str, None, None]: + def link_to_folder(link: bs4.element.Tag) -> str: + raw_url: str = str(link.get("href", default="")) + url: ParseResult = urlparse(raw_url) + if url.scheme or url.netloc: + return "" + url_path: str = posixpath.normpath(url.path) + if "/" in url_path or url_path == "." or url_path == "..": + return "" + return url_path + + try: + soup: bs4.BeautifulSoup = bs4.BeautifulSoup(html_doc, "html.parser") + for link in soup.find_all("a"): + folder: str = link_to_folder(link) + if not folder: + continue + if folder.startswith(filter_category): + yield folder + if filter_category == "tools" and folder == "sdktool": + yield folder + except Exception as e: + raise ArchiveConnectionError( + f"Failed to retrieve the expected HTML page at {html_url}", + suggested_action=[ + "Check your network connection.", + f"Make sure that you can access {html_url} in your web browser.", + ], + ) from e + + def get_versions_extensions(self, html_doc: str, category: str) -> Iterator[Tuple[Optional[Version], str]]: + def folder_to_version_extension(folder: str) -> Tuple[Optional[Version], str]: + + ext = "" + ver = "" + + # Special case for Qt6.7 unique format + if folder.startswith("qt6_7_"): + # Split the input into version and extension parts + # For qt6_7_3_arm64_v8a, we want to extract "6_7_3" and "arm64_v8a" + # Should not be more than qt6_7_3_backup (extension should not have _, but you know...) + + # Remove the "qt" prefix first + remainder = folder[2:] + + # Split the first 3 parts for the version (6_7_3) + version_parts = remainder.split("_", 3)[:3] + ver = "_".join(version_parts) + + # Everything after version is the extension + if len(remainder.split("_", 3)) > 3: + ext = remainder.split("_", 3)[3] + else: + ext = "" + else: + components = folder.split("_", maxsplit=2) + ext = "" if len(components) < 3 else components[2] + ver = "" if len(components) < 2 else components[1] + return ( + get_semantic_version(qt_ver=ver, is_preview="preview" in ext), + ext, + ) + + return map( + folder_to_version_extension, + self.iterate_folders(html_doc, self.base_url, filter_category=category), + ) + + @staticmethod + def _has_nonempty_downloads(element: Element) -> bool: + """Returns True if the element has a nonempty '' tag""" + downloads = element.find("DownloadableArchives") + update_file = element.find("UpdateFile") + if downloads is None or update_file is None: + return False + uncompressed_size = int(update_file.attrib["UncompressedSize"]) + return downloads.text is not None and uncompressed_size >= Settings.min_module_size + + def _get_qt_version_str(self, version: Version) -> str: + """Returns a Qt version, without dots, that works in the Qt repo urls and Updates.xml files""" + # NOTE: The url at `///qt5_590/` does not exist; the real one is `qt5_59` + patch = ( + "" + if version.prerelease or self.archive_id.is_preview() or version in SimpleSpec("5.9.0") + else str(version.patch) + ) + return f"{version.major}{version.minor}{patch}" + + def _fetch_module_metadata(self, folder: str, predicate: Optional[Callable[[Element], bool]] = None): + rest_of_url = posixpath.join(self.archive_id.to_url(), folder, "Updates.xml") + xml = self.fetch_http(rest_of_url) if not Settings.ignore_hash else self.fetch_http(rest_of_url, False) + return xml_to_modules( + xml, + predicate=predicate if predicate else MetadataFactory._has_nonempty_downloads, + ) + + def _fetch_extension_metadata(self, url: str, predicate: Optional[Callable[[Element], bool]] = None): + rest_of_url = posixpath.join(url, "Updates.xml") + xml = self.fetch_http(rest_of_url) if not Settings.ignore_hash else self.fetch_http(rest_of_url, False) + return xml_to_modules( + xml, + predicate=predicate if predicate else MetadataFactory._has_nonempty_downloads, + ) + + def fetch_modules(self, version: Version, arch: str) -> List[str]: + """Returns list of modules""" + extension = QtRepoProperty.extension_for_arch(arch, version >= Version("6.0.0")) + qt_ver_str = self._get_qt_version_str(version) + # Example: re.compile(r"^(preview\.)?qt\.(qt5\.)?590\.(.+)$") + pattern = re.compile(r"^(preview\.)?qt\.(qt" + str(version.major) + r"\.)?" + qt_ver_str + r"\.(.+)$") + modules_meta = self._fetch_module_metadata(self.archive_id.to_folder(version, qt_ver_str, extension)) + + def to_module_arch(name: str) -> Tuple[Optional[str], Optional[str]]: + _match = pattern.match(name) + if not _match: + return None, None + module_with_arch = _match.group(3) + if "." not in module_with_arch: + return module_with_arch, None + module, arch = module_with_arch.rsplit(".", 1) + if module.startswith("addons."): + module = module[len("addons.") :] + return module, arch + + modules: Set[str] = set() + for name in modules_meta.keys(): + module, _arch = to_module_arch(name) + if _arch == arch: + modules.add(cast(str, module)) + + ext_pattern = re.compile(r"^extensions\." + r"(?P[^.]+)\." + qt_ver_str + r"\." + arch + r"$") + for ext in QtRepoProperty.known_extensions(version): + try: + ext_meta = self._fetch_extension_metadata(self.archive_id.to_extension_folder(ext, qt_ver_str, arch)) + for key, value in ext_meta.items(): + ext_match = ext_pattern.match(key) + if ext_match is not None: + module = ext_match.group("module") + if module is not None: + modules.add(ext) + except (ChecksumDownloadFailure, ArchiveDownloadError): + pass + return sorted(modules) + + @staticmethod + def require_text(element: Element, key: str) -> str: + node = element.find(key) + if node is None: + raise ArchiveListError(f"Downloaded metadata does not match the expected structure. Missing key: {key}") + return node.text or "" + + def fetch_long_modules(self, version: Version, arch: str) -> ModuleData: + """Returns long listing of modules""" + extension = QtRepoProperty.extension_for_arch(arch, version >= Version("6.0.0")) + qt_ver_str = self._get_qt_version_str(version) + # Example: re.compile(r"^(preview\.)?qt\.(qt5\.)?590(\.addons)?\.(?P[^.]+)\.gcc_64$") + # qt.qt6.680.addons.qtwebsockets.win64_msvc2022_64 + # qt.qt6.680.debug_info.win64_msvc2022_64 + pattern = re.compile( + r"^(preview\.)?qt\.(qt" + + str(version.major) + + r"\.)?" + + qt_ver_str + + r"(\.addons)?\.(?P[^.]+)\." + + arch + + r"$" + ) + + def matches_arch(element: Element) -> bool: + return bool(pattern.match(MetadataFactory.require_text(element, "Name"))) + + modules_meta = self._fetch_module_metadata(self.archive_id.to_folder(version, qt_ver_str, extension), matches_arch) + m: Dict[str, Dict[str, str]] = {} + for key, value in modules_meta.items(): + match = pattern.match(key) + if match is not None: + module = match.group("module") + if module is not None: + m[module] = value + + # Examples: extensions.qtwebengine.680.debug_information + # extensions.qtwebengine.680.win64_msvc2022_64 + ext_pattern = re.compile(r"^extensions\." + r"(?P[^.]+)\." + qt_ver_str + r"\." + arch + r"$") + for ext in QtRepoProperty.known_extensions(version): + try: + ext_meta = self._fetch_extension_metadata(self.archive_id.to_extension_folder(ext, qt_ver_str, arch)) + for key, value in ext_meta.items(): + ext_match = ext_pattern.match(key) + if ext_match is not None: + module = ext_match.group("module") + if module is not None: + m[module] = value + except (ChecksumDownloadFailure, ArchiveDownloadError): + pass + return ModuleData(m) + + def fetch_modules_sde(self, cmd_type: str, version: Version) -> List[str]: + """Returns list of modules for src/doc/examples""" + assert cmd_type in ("doc", "examples") and self.archive_id.target in ( + "desktop", + "qt", + ), "Internal misuse of fetch_modules_sde" + qt_ver_str = self._get_qt_version_str(version) + modules_meta = self._fetch_module_metadata( + self.archive_id.to_folder(version, qt_ver_str, QtRepoProperty.sde_ext(version)) + ) + # pattern: Match all names "qt.qt5.12345.doc.(\w+) + pattern = re.compile(r"^qt\.(qt" + str(version.major) + r"\.)?" + qt_ver_str + r"\." + cmd_type + r"\.(.+)$") + + modules: List[str] = [] + for name in modules_meta: + _match = pattern.match(name) + if _match: + modules.append(_match.group(2)) + return modules + + def fetch_archives_sde(self, cmd_type: str, version: Version) -> List[str]: + """Returns list of archives for src/doc/examples""" + assert cmd_type in ("src", "doc", "examples") and self.archive_id.target in ( + "desktop", + "qt", + ), "Internal misuse of fetch_archives_sde" + return self.fetch_archives(version, cmd_type, [], is_sde=True) + + def fetch_archives(self, version: Version, arch: str, modules: List[str], is_sde: bool = False) -> List[str]: + extension = ( + QtRepoProperty.sde_ext(version) + if is_sde + else QtRepoProperty.extension_for_arch(arch, version >= Version("6.0.0")) + ) + qt_version_str = self._get_qt_version_str(version) + nonempty = MetadataFactory._has_nonempty_downloads + + def all_modules(element: Element) -> bool: + _module, _arch = MetadataFactory.require_text(element, "Name").split(".")[-2:] + return _arch == arch and _module != qt_version_str and nonempty(element) + + def specify_modules(element: Element) -> bool: + _module, _arch = MetadataFactory.require_text(element, "Name").split(".")[-2:] + return _arch == arch and _module in modules and nonempty(element) + + def no_modules(element: Element) -> bool: + name: Optional[str] = getattr(element.find("Name"), "text", None) + return name is not None and name.endswith(f".{qt_version_str}.{arch}") and nonempty(element) + + predicate = no_modules if not modules else all_modules if "all" in modules else specify_modules + try: + mod_metadata = self._fetch_module_metadata( + self.archive_id.to_folder(version, qt_version_str, extension), predicate=predicate + ) + except (AttributeError, ValueError) as e: + raise ArchiveListError(f"Downloaded metadata is corrupted. {e}") from e + + # Did we find all requested modules? + if modules and "all" not in modules: + requested_set = set(modules) + actual_set = set([_name.split(".")[-2] for _name in mod_metadata.keys()]) + not_found = sorted(requested_set.difference(actual_set)) + if not_found: + raise CliInputError( + f"The requested modules were not located: {not_found}", suggested_action=suggested_follow_up(self) + ) + + csv_lists = [mod["DownloadableArchives"] for mod in mod_metadata.values()] + return sorted(set([arc.split("-")[0] for csv in csv_lists for arc in csv.split(", ")])) + + def describe_filters(self) -> str: + if self.spec is None: + return str(self.archive_id) + return "{} with spec {}".format(self.archive_id, self.spec) + + def fetch_default_desktop_arch(self, version: Version, is_msvc: bool = False) -> str: + assert self.archive_id.target == "desktop", "This function is meant to fetch desktop architectures" + if self.archive_id.host == "linux": + if version >= Version("6.7.0"): + return "linux_gcc_64" + else: + return "gcc_64" + elif self.archive_id.host == "linux_arm64": + return "linux_gcc_arm64" + elif self.archive_id.host == "mac": + return "clang_64" + elif self.archive_id.host == "windows" and is_msvc: + if version >= Version("6.8.0"): + return "win64_msvc2022_64" + else: + return "win64_msvc2019_64" + arches = [arch for arch in self.fetch_arches(version) if QtRepoProperty.MINGW_ARCH_PATTERN.match(arch)] + selected_arch = QtRepoProperty.select_default_mingw(arches, is_dir=False) + if not selected_arch: + raise EmptyMetadata("No default desktop architecture available") + return selected_arch + + +def suggested_follow_up(meta: MetadataFactory) -> List[str]: + """Makes an informed guess at what the user got wrong, in the event of an error.""" + msg = [] + list_cmd = "list-tool" if meta.archive_id.is_tools() else "list-qt" + base_cmd = "aqt {0} {1.host} {1.target}".format(list_cmd, meta.archive_id) + versions_msg = f"Please use '{base_cmd}' to show versions of Qt available." + arches_msg = f"Please use '{base_cmd} --arch ' to show architectures available." + + if meta.archive_id.is_tools() and meta.request_type == "tool variant names": + msg.append(f"Please use '{base_cmd}' to check what tools are available.") + elif meta.spec is not None: + msg.append( + f"Please use '{base_cmd}' to check that versions of {meta.archive_id.category} " + f"exist within the spec '{meta.spec}'." + ) + elif meta.request_type in ("architectures", "modules", "extensions"): + msg.append(f"Please use '{base_cmd}' to show versions of Qt available.") + if meta.request_type == "modules": + msg.append(f"Please use '{base_cmd} --arch ' to list valid architectures.") + elif meta.request_type == "archives for modules": + msg.extend([versions_msg, arches_msg, f"Please use '{base_cmd} --modules ' to show modules available."]) + elif meta.request_type == "archives for qt": + msg.extend([versions_msg, arches_msg]) + + return msg + + +def show_list(meta: MetadataFactory): + try: + output = meta.getList() + if not output: + raise EmptyMetadata( + f"No {meta.request_type} available for this request.", suggested_action=suggested_follow_up(meta) + ) + if isinstance(output, Versions): + print(format(output)) + elif isinstance(output, TableMetadata): + width: int = shutil.get_terminal_size((0, 40)).columns + if width == 0: # notty ? + print(format(output, "{:0t}")) + elif width < 95: # narrow terminal + print(format(output, "{:T}")) + else: + print("{0:{1}t}".format(output, width)) + elif meta.archive_id.is_tools(): + print(*output, sep="\n") + else: + print(*output, sep=" ") + except (ArchiveDownloadError, ArchiveConnectionError) as e: + e.append_suggested_follow_up(suggested_follow_up(meta)) + raise e from e diff --git a/python/py313/Lib/site-packages/aqt/settings.ini b/python/py313/Lib/site-packages/aqt/settings.ini new file mode 100644 index 0000000000000000000000000000000000000000..5a176c3aec84cb6de7af6076b7b95f4b3c65a010 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/settings.ini @@ -0,0 +1,256 @@ +[DEFAULTS] + +[aqt] +concurrency : 4 +baseurl : https://download.qt.io +7zcmd : 7z +print_stacktrace_on_error : False +always_keep_archives : False +archive_download_location : . +min_module_size : 41 + +[requests] +connection_timeout : 3.5 +response_timeout : 30 +max_retries_on_connection_error : 5 +retry_backoff : 0.1 +max_retries_on_checksum_error : 5 +max_retries_to_retrieve_hash : 5 +hash_algorithm : sha256 +INSECURE_NOT_FOR_PRODUCTION_ignore_hash : False + +[qtofficial] +unattended : True +installer_timeout : 1800 +operation_does_not_exist_error : Ignore +overwrite_target_directory : No +stop_processes_for_updates : Ignore +installation_error_with_cancel : Ignore +installation_error_with_ignore : Ignore +associate_common_filetypes : Yes +telemetry : No +cache_path : +temp_dir : + +[mirrors] +trusted_mirrors : + https://download.qt.io +blacklist : + http://mirrors.ocf.berkeley.edu + http://mirrors.tuna.tsinghua.edu.cn + http://mirrors.geekpie.club +fallbacks : + https://qtproject.mirror.liquidtelecom.com/ + https://mirrors.aliyun.com/qt/ + https://mirrors.ustc.edu.cn/qtproject/ + https://ftp.jaist.ac.jp/pub/qtproject/ + https://ftp.yz.yamagata-u.ac.jp/pub/qtproject/ + https://qt-mirror.dannhauer.de/ + https://ftp.fau.de/qtproject/ + https://mirror.netcologne.de/qtproject/ + https://mirrors.dotsrc.org/qtproject/ + https://www.nic.funet.fi/pub/mirrors/download.qt-project.org/ + https://master.qt.io/ + https://mirrors.ukfast.co.uk/sites/qt.io/ + https://ftp2.nluug.nl/languages/qt/ + https://ftp1.nluug.nl/languages/qt/ + https://qt.mirror.constant.com/ + +[kde_patches] +patches : + 0001-toolchain.prf-Use-vswhere-to-obtain-VS-installation-.patch + 0002-Fix-allocated-memory-of-QByteArray-returned-by-QIODe.patch + 0003-Update-CLDR-to-v37-adding-Nigerian-Pidgin-as-a-new-l.patch + 0004-QLayout-docs-explain-better-what-the-QWidget-ctor-ar.patch + 0005-QMacStyle-fix-tab-rendering.patch + 0006-QMacStyle-more-pixel-refinements.patch + 0007-Deprecate-ordering-on-QItemSelectionRange.patch + 0008-Deprecate-QLocale-Language-entries-that-no-locale-da.patch + 0009-Deprecate-old-aliases-for-two-countries-and-several-.patch + 0010-QAbstractItemModelTester-don-t-rely-on-hasChildren.patch + 0011-Doc-Remove-mentioning-of-old-macos-versions-from-QSe.patch + 0012-Pass-SameSite-through-QNetworkCookie.patch + 0013-doc-fix-typo-consise-concise.patch + 0014-Selftest-copy-XAUTHORITY-environment-variable.patch + 0015-Fix-delay-first-time-a-font-is-used.patch + 0016-Fix-QScreen-orientation-not-being-updated-when-setti.patch + 0017-Android-Request-cursor-to-be-in-proper-position.patch + 0018-testlib-Let-logger-report-whether-it-is-logging-to-s.patch + 0019-Android-disable-Gradle-caching-by-default.patch + 0020-Android-replace-stacktrace-with-debug-message-in-sea.patch + 0021-Use-void-instead-of-Q_UNUSED.patch + 0022-Don-t-show-QPushButton-as-hovered-unless-the-mouse-i.patch + 0023-MinGW-Fix-assert-in-QCoreApplication-arguments-when-.patch + 0024-QCombobox-propagate-the-palette-to-the-embedded-line.patch + 0025-QMarginsF-document-that-isNull-operator-operator-are.patch + 0026-qmake-vcxproj-Fix-handling-of-extra-compiler-outputs.patch + 0027-Android-fix-documentation-about-ANDROID_EXTRA_LIBS.patch + 0028-Offscreen-QPA-implement-a-native-interface.patch + 0029-DropSite-example-support-markdown.patch + 0030-Do-not-define-dynamic_cast.patch + 0031-Android-fix-crash-by-passing-the-right-Handle-to-dls.patch + 0032-testlib-Add-private-API-to-add-test-logger.patch + 0033-Update-third-party-md4c-to-version-0.4.6.patch + 0034-moc-Handle-include-in-enum-take-2.patch + 0035-InputMethod-should-call-reset-function-when-proxywid.patch + 0036-Add-possibility-to-set-QNX-Screen-pipeline-value.patch + 0037-qglobal-Only-define-QT_ENSURE_STACK_ALIGNED_FOR_SSE-.patch + 0038-macOS-FreeType-fix-crash-with-non-printable-unicode.patch + 0039-Linux-fix-crash-in-AtSpi-adaptor-when-handling-windo.patch + 0040-Add-_MSC_VER-check-to-MSVC-ARM-compiler-workaround.patch + 0041-QMap-suppress-warning-about-strict-aliasing-violatio.patch + 0042-Add-changes-file-for-Qt-5.15.2.patch + 0043-Set-the-url-to-have-the-AtNx-filename-if-one-is-foun.patch + 0044-QMap-don-t-tell-everyone-QMapNode-has-no-friends.patch + 0045-QNAM-Work-around-QObject-finicky-orphan-cleanup-deta.patch + 0046-xcb-ensure-that-available-glx-version-is-greater-tha.patch + 0047-Protect-QImage-colorspace-transform-on-shutdown.patch + 0048-Fix-qstylesheetstyle-clip-border-error.patch + 0049-Correct-processEvents-documentation.patch + 0050-Update-CLDR-to-v38.patch + 0051-Fix-compilation-when-using-no-mimetype-database.patch + 0052-Reduce-memory-reallocations-in-QTextTablePrivate-upd.patch + 0053-Fix-regular-expression-initialize-with-incorrect-fil.patch + 0054-Cocoa-Allow-CMD-H-to-hide-the-application-when-a-too.patch + 0055-Fix-pcre2-feature-conditions.patch + 0056-Q_PRIMITIVE_TYPE-improve-the-documentation.patch + 0057-QAsn1Element-Read-value-in-blocks-to-avoid-oom-at-wr.patch + 0058-Android-Don-t-use-putIfAbsent-as-that-is-not-availab.patch + 0059-QMutex-order-reads-from-QMutexPrivate-waiters-and-QB.patch + 0060-Android-Add-the-QtAndroidBearer.jar-to-the-jar-depen.patch + 0061-Android-Add-the-required-linker-flags-for-unwinding-.patch + 0062-Android-recommend-against-using-ANDROID_ABIS-inside-.patch + 0063-Android-fix-android-java-and-templates-targets-with-.patch + 0064-QCharRef-properly-disable-assignment-from-char.patch + 0065-Android-Treat-ACTION_CANCEL-as-TouchPointReleased.patch + 0066-Fix-misidentification-of-some-shearing-QTransforms-a.patch + 0067-Fix-QGraphicsItem-crash-if-click-right-button-of-mou.patch + 0068-Bump-version.patch + 0069-Android-Ensure-windows-always-have-a-geometry-on-cre.patch + 0070-macOS-Account-for-Big-Sur-always-enabling-layer-back.patch + 0071-Fix-shaping-problems-on-iOS-14-macOS-11.patch + 0072-Link-to-qAlpha-in-qRgb-and-qRgba-docs.patch + 0073-HTTP2-fix-crash-from-assertion.patch + 0074-Fuzzing-Add-a-test-for-QDateTime-fromString.patch + 0075-QSocks5SocketEngine-Fix-out-of-bounds-access-of-QBA.patch + 0076-Use-QTRY_COMPARE-in-an-attempt-to-make-the-test-less.patch + 0077-Doc-Document-QGradient-Preset-enum-values.patch + 0078-Doc-Fix-documentation-warnings-for-Qt-XML.patch + 0079-Doc-Fix-documentation-warnings-in-Qt-Network.patch + 0080-Ensure-that-QMenu-is-polished-before-setting-the-scr.patch + 0081-widgets-Don-t-report-new-focus-object-during-clearFo.patch + 0082-QDtls-remove-redundant-RAII-struct.patch + 0083-macOS-Propagate-device-pixel-ratio-of-system-tray-ic.patch + 0084-tst_qocsp-improve-code-coverage.patch + 0085-Doc-explain-how-to-create-a-test-touch-device-for-us.patch + 0086-macOS-Upgrade-supported-SDK-to-11.0.patch + 0087-Fix-logic-error-in-QString-replace-ch-after-cs.patch + 0088-Be-more-consistent-when-converting-JSON-values-from-.patch + 0089-QCoreApplication-add-more-information-to-processEven.patch + 0090-Fix-QSFPM-not-emitting-dataChanged-when-source-model.patch + 0091-Android-Fix-android-accessibility-not-being-set-acti.patch + 0092-Fix-x-height-name-in-stylesheet-docs.patch + 0093-QMutex-Work-around-ICC-bug-in-dealing-with-constexpr.patch + 0094-wasm-fix-resizing-of-qwidget-windows.patch + 0095-Avoid-integer-overflow-and-division-by-zero.patch + 0096-QPasswordDigestor-improve-code-coverage.patch + 0097-QStackedLayout-fix-a-memory-leak.patch + 0098-Limit-value-in-setFontWeightFromValue.patch + 0099-Doc-Fix-documentation-of-qmake-s-exists-function.patch + 0100-QVLA-do-not-include-QtTest.patch + 0101-Clean-up-docs-of-QCalendar-related-QLocale-toString-.patch + 0102-Change-android-target-SDK-version-to-29.patch + 0103-QVLA-always-use-new-to-create-new-objects.patch + 0104-QPushButton-fix-support-of-style-sheet-rule-for-text.patch + 0105-Limit-pen-width-to-maximal-32767.patch + 0106-Doc-Consistently-use-book-style-capitalization-for-Q.patch + 0107-qstring.h-fix-warnings-about-shortening-qsizetype-to.patch + 0108-Fix-invalid-QSortFilterProxyModel-dataChanged-parame.patch + 0109-Minor-refactor-of-installMetaFile.patch + 0110-Return-a-more-useful-date-time-on-parser-failure-in-.patch + 0111-QCalendar-increase-coverage-by-tests.patch + 0112-Bounds-check-time-zone-offsets-when-parsing.patch + 0113-Network-self-test-make-it-work-with-docker-container.patch + 0114-QSslConfiguration-improve-code-coverage.patch + 0115-Add-new-way-to-mess-up-projects-with-QMAKE_INSTALL_R.patch + 0116-Install-3rd-party-headers-and-meta-for-static-builds.patch + 0117-Create-qtlibjpeg-for-jpeg-image-plugin.patch + 0118-QStandardPaths-Don-t-change-permissions-of-XDG_RUNTI.patch + 0119-tst_QSslCertificate-improve-code-coverage.patch + 0120-Let-QXcbConnection-getTimestamp-properly-exit-when-X.patch + 0121-QDtls-cookie-verifier-make-sure-a-server-can-re-use-.patch + 0122-QMacStyle-remove-vertical-adjustment-for-inactive-ta.patch + 0123-Revert-xcb-add-xcb-util-dependency-for-xcb-image.patch + 0124-Containers-call-constructors-even-for-primitive-type.patch + 0125-Android-print-tailored-warning-if-qml-dependency-pat.patch + 0126-Cosmetic-stroker-avoid-overflows-for-non-finite-coor.patch + 0127-QSslCipher-improve-its-code-coverage-and-auto-tests.patch + 0128-tst_qsslkey-handle-QT_NO_SSL-properly.patch + 0129-Add-the-Qt-6.0-deprecation-macros.patch + 0130-wasm-fix-mouse-double-click.patch + 0131-Android-avoid-reflection-with-ClipData-addItem.patch + 0132-QHeaderView-fix-spurious-sorting.patch + 0133-Fix-exception-with-Android-5.x.patch + 0134-Http2-Remove-errored-out-requests-from-queue.patch + 0135-Http2-don-t-call-ensureConnection-when-there-s-no-re.patch + 0136-Fix-QTranslator-load-search-order-not-following-uiLa.patch + 0137-Avoid-signed-overflow-in-moc.patch + 0138-Android-Kill-calls-to-deprecated-func-in-API-29.patch + 0139-Doc-Improve-_CAST_FROM_ASCII-documentation.patch + 0140-Improve-documented-function-argument-names.patch + 0141-Fix-QImage-setPixelColor-on-RGBA64_Premultiplied.patch + 0142-macOS-Make-sure-that-the-reserved-characters-are-not.patch + 0143-Enable-testing-for-whether-a-calendar-registered-its.patch + 0144-tests-add-a-shortcut-to-quit-app-in-allcursors.patch + 0145-QSslSocket-Don-t-call-transmit-in-unencrypted-mode.patch + 0146-QStringView-operator-operator-operator-currently-Qt6.patch + 0147-QCborStreamReader-move-the-readStringChunk-code-to-t.patch + 0148-Improve-the-documentation-for-QElapsedTimer-restart-.patch + 0149-QSslSocket-verify-do-not-alter-the-default-configura.patch + 0150-Fix-tst_QFontDatabase-aliases-failure-with-ambiguous.patch + 0151-QStyleAnimation-make-sure-the-last-frame-of-animatio.patch + 0152-PCRE-update-to-10.36.patch + 0153-tst_QCborValue-adjust-the-size-of-the-minimum-string.patch + 0154-macOS-Always-allow-interacting-with-popup-windows-du.patch + 0155-macOS-Add-missing-QT_MANGLE_NAMESPACE.patch + 0156-QSplashScreen-draw-pixmap-with-SmoothTransfrom.patch + 0157-Android-Qml-accessibility-fixes.patch + 0158-Http2-set-the-reply-s-error-code-and-string-on-error.patch + 0159-Try-again-to-fix-Clang-s-Wconstant-logical-operand-w.patch + 0160-Revert-Android-print-tailored-warning-if-qml-depende.patch + 0161-QUrl-fix-parsing-of-empty-IPv6-addresses.patch + 0162-tst_QSslError-improve-the-code-coverage-as-pointed-a.patch + 0163-macOS-Disable-WA_QuitOnClose-on-menu-item-widget-con.patch + 0164-QString-fix-count-QRegularExpression.patch + 0165-QString-lastIndexOf-fix-off-by-one-for-zero-length-m.patch + 0166-secureudpclient-a-speculative-fix-for-non-reproducib.patch + 0167-Android-don-t-use-avx-and-avx2-when-building-for-And.patch + 0168-Fuzzing-Provide-link-to-oss-fuzz.patch + 0169-Blacklist-tst_QMdiArea-updateScrollBars-on-macos.patch + 0170-Fix-build-with-GCC-11-include-limits.patch + 0171-Build-fixes-for-GCC-11.patch + 0172-Partially-revert-813a928c7c3cf98670b6043149880ed5c95.patch + 0173-Fix-removing-columns-when-QSortFilterProxyModel-has-.patch + 0174-Fix-get-out-of-bounds-index-in-QSortFilterProxyModel.patch + 0175-Fix-handling-of-surrogates-in-QBidiAlgorithm.patch + 0176-Avoid-undefined-color-values-in-corrupt-xpm-image.patch + 0177-Gracefully-reject-requests-for-absurd-font-sizes.patch + 0178-Don-t-own-unique-name-for-QDBusTrayIcon.patch + 0179-QAbstractItemModelTester-fix-false-positive-when-mod.patch + 0180-Fix-QAbstractItemModelTester-false-positive.patch + 0181-Deprecate-QMutex-in-recursive-mode.patch + 0182-Fix-QAbstractItemModelTester-false-positive.patch + 0183-Fix-crash-on-serializing-default-constructed-QTimeZo.patch + 0184-Fix-QTreeModel-calling-beginRemoveRows-twice.patch + 0185-QConcatenateTablesProxyModel-skip-dataChanged-in-hid.patch + 0186-QComboBox-fix-select-all-columns-in-the-view.patch + 0187-QTableView-honor-spans-when-calculating-height-width.patch + 0188-TableView-Trigger-the-resizing-of-editors-resizing-a.patch + 0189-Fix-no-mapping-for-SysReq-key.patch + 0190-qdbus-add-support-for-aay-QByteArrayList.patch + 0191-QRandom-drop-a-usage-of-std-is_literal_type.patch + 0192-fix-Optimize-the-performance-of-the-inotify-file-sys.patch + 0193-Remove-the-unnecessary-template-parameter-from-the-c.patch + 0194-Fix-memory-leak-when-using-small-caps-font.patch + 0195-Make-sure-_q_printerChanged-is-called-even-if-only-p.patch + 0196-fix-Alt-shortcut-on-non-US-layouts.patch \ No newline at end of file diff --git a/python/py313/Lib/site-packages/aqt/updater.py b/python/py313/Lib/site-packages/aqt/updater.py new file mode 100644 index 0000000000000000000000000000000000000000..0b307b45e0ff97abcb13f7ad8baf34e935c40119 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/updater.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python +# +# Copyright (C) 2019-2021 Hiroshi Miura +# +# 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. +import logging +import os +import re +import stat +import subprocess +from logging import getLogger +from pathlib import Path +from typing import Dict, List, Optional, Union + +import patch_ng as patch + +from aqt.archives import TargetConfig +from aqt.exceptions import UpdaterError +from aqt.helper import Settings +from aqt.metadata import ArchiveId, MetadataFactory, QtRepoProperty, SimpleSpec, Version + +dir_for_version = QtRepoProperty.dir_for_version + + +def unpatched_paths() -> List[str]: + return [ + "/home/qt/work/install/", + "/Users/qt/work/install/", + "\\home\\qt\\work\\install\\", + "\\Users\\qt\\work\\install\\", + ] + + +class Updater: + def __init__(self, prefix: Path, logger) -> None: + self.logger = logger + self.prefix = prefix + self.qmake_path: Optional[Path] = None + self.qconfigs: Dict[str, str] = {} + + def _patch_binfile(self, file: Path, key: bytes, newpath: bytes): + """Patch binary file with key/value""" + st = file.stat() + data = file.read_bytes() + idx = data.find(key) + if idx < 0: + return + assert len(newpath) < 256, "Qt Prefix path is too long(255)." + oldlen = data[idx + len(key) :].find(b"\0") + assert oldlen >= 0 + value = newpath + b"\0" * (oldlen - len(newpath)) + data = data[: idx + len(key)] + value + data[idx + len(key) + len(value) :] + file.write_bytes(data) + os.chmod(str(file), st.st_mode) + + def _append_string(self, file: Path, val: str): + """Append string to file""" + st = file.stat() + data = file.read_text("UTF-8") + data += val + file.write_text(data, "UTF-8") + os.chmod(str(file), st.st_mode) + + def _patch_textfile(self, file: Path, old: Union[str, re.Pattern], new: str, *, is_executable: bool = False): + st = file.stat() + file_mode = st.st_mode | (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH if is_executable else 0) + data = file.read_text("UTF-8") + if isinstance(old, re.Pattern): + data = old.sub(new, data) + else: + data = data.replace(old, new) + file.write_text(data, "UTF-8") + os.chmod(str(file), file_mode) + + def _detect_qmake(self) -> bool: + """detect Qt configurations from qmake.""" + for qmake_path in [ + self.prefix.joinpath("bin", "qmake"), + self.prefix.joinpath("bin", "qmake.exe"), + ]: + if not qmake_path.exists(): + continue + try: + result = subprocess.run([str(qmake_path), "-query"], stdout=subprocess.PIPE) + except (subprocess.SubprocessError, IOError, OSError): + return False + if result.returncode == 0: + self.qmake_path = qmake_path + for line in result.stdout.splitlines(): + vals = line.decode("UTF-8").split(":") + self.qconfigs[vals[0]] = vals[1] + return True + return False + + def patch_prl(self, oldvalue): + for prlfile in self.prefix.joinpath("lib").glob("*.prl"): + self.logger.info("Patching {}".format(prlfile)) + self._patch_textfile(prlfile, oldvalue, "$$[QT_INSTALL_LIBS]") + + def patch_pkgconfig(self, oldvalue, os_name): + for pcfile in self.prefix.joinpath("lib", "pkgconfig").glob("*.pc"): + self.logger.info("Patching {}".format(pcfile)) + self._patch_textfile( + pcfile, + "prefix={}".format(oldvalue), + "prefix={}".format(str(self.prefix)), + ) + if os_name == "mac": + self._patch_textfile( + pcfile, + "-F{}".format(os.path.join(oldvalue, "lib")), + "-F{}".format(os.path.join(str(self.prefix), "lib")), + ) + + def patch_libtool(self, oldvalue, os_name): + for lafile in self.prefix.joinpath("lib").glob("*.la"): + self.logger.info("Patching {}".format(lafile)) + self._patch_textfile( + lafile, + "libdir='={}'".format(oldvalue), + "libdir='={}'".format(os.path.join(str(self.prefix), "lib")), + ) + self._patch_textfile( + lafile, + "libdir='{}'".format(oldvalue), + "libdir='{}'".format(os.path.join(str(self.prefix), "lib")), + ) + self._patch_textfile( + lafile, + "-L={}".format(oldvalue), + "-L={}".format(os.path.join(str(self.prefix), "lib")), + ) + self._patch_textfile( + lafile, + "-L{}".format(oldvalue), + "-L{}".format(os.path.join(str(self.prefix), "lib")), + ) + if os_name == "mac": + self._patch_textfile( + lafile, + "-F={}".format(oldvalue), + "-F={}".format(os.path.join(str(self.prefix), "lib")), + ) + self._patch_textfile( + lafile, + "-F{}".format(oldvalue), + "-F{}".format(os.path.join(str(self.prefix), "lib")), + ) + + def patch_qmake(self): + """Patch to qmake binary""" + if self._detect_qmake(): + if self.qmake_path is None: + return + self.logger.info("Patching {}".format(str(self.qmake_path))) + self._patch_binfile( + self.qmake_path, + key=b"qt_prfxpath=", + newpath=bytes(str(self.prefix), "UTF-8"), + ) + self._patch_binfile( + self.qmake_path, + key=b"qt_epfxpath=", + newpath=bytes(str(self.prefix), "UTF-8"), + ) + self._patch_binfile( + self.qmake_path, + key=b"qt_hpfxpath=", + newpath=bytes(str(self.prefix), "UTF-8"), + ) + + def patch_qt_scripts(self, base_dir, version_dir: str, os_name: str, desktop_arch_dir: str, version: Version): + sep = "\\" if os_name.startswith("windows") else "/" + patched = sep.join([base_dir, version_dir, desktop_arch_dir, "bin"]) + + def patch_script(script_name): + script_path = self.prefix / "bin" / (script_name + ".bat" if os_name.startswith("windows") else script_name) + self.logger.info(f"Patching {script_path}") + for unpatched in unpatched_paths(): + self._patch_textfile(script_path, f"{unpatched}bin", patched, is_executable=True) + + patch_script("qmake") + if version >= Version("6.2.2"): + patch_script("qtpaths") + if version >= Version("6.5.0"): + patch_script("qmake6") + patch_script("qtpaths6") + + def patch_qtcore(self, target): + """patch to QtCore""" + if target.os_name == "mac": + lib_dir = self.prefix.joinpath("lib", "QtCore.framework") + components = ["QtCore", "QtCore_debug"] + elif target.os_name == "linux": + lib_dir = self.prefix.joinpath("lib") + components = ["libQt5Core.so"] + elif target.os_name.startswith("windows"): + lib_dir = self.prefix.joinpath("bin") + components = ["Qt5Cored.dll", "Qt5Core.dll"] + else: + return + for component in components: + if lib_dir.joinpath(component).exists(): + qtcore_path = lib_dir.joinpath(component).resolve() + self.logger.info("Patching {}".format(qtcore_path)) + newpath = bytes(str(self.prefix), "UTF-8") + self._patch_binfile(qtcore_path, b"qt_prfxpath=", newpath) + + def make_qtconf(self, base_dir, qt_version, arch_dir): + """Prepare qt.conf""" + with open(os.path.join(base_dir, qt_version, arch_dir, "bin", "qt.conf"), "w") as f: + f.write("[Paths]\n") + f.write("Prefix=..\n") + + def make_qtenv2(self, base_dir, qt_version, arch_dir): + """Prepare qtenv2.bat""" + with open(os.path.join(base_dir, qt_version, arch_dir, "bin", "qtenv2.bat"), "w") as f: + f.write("@echo off\n") + f.write("echo Setting up environment for Qt usage...\n") + f.write("set PATH={};%PATH%\n".format(os.path.join(base_dir, qt_version, arch_dir, "bin"))) + f.write("cd /D {}\n".format(os.path.join(base_dir, qt_version, arch_dir))) + f.write("echo Remember to call vcvarsall.bat to complete environment setup!\n") + + def set_license(self, base_dir: str, qt_version: str, arch_dir: str): + """Update qconfig.pri as OpenSource""" + with open(os.path.join(base_dir, qt_version, arch_dir, "mkspecs", "qconfig.pri"), "r+") as f: + lines = f.readlines() + f.seek(0) + f.truncate() + for line in lines: + if line.startswith("QT_EDITION ="): + line = "QT_EDITION = OpenSource\n" + if line.startswith("QT_LICHECK ="): + line = "QT_LICHECK =\n" + f.write(line) + + def patch_target_qt_conf(self, base_dir: str, qt_version: str, arch_dir: str, os_name: str, desktop_arch_dir: str): + target_qt_conf = self.prefix / "bin" / "target_qt.conf" + self.logger.info(f"Patching {target_qt_conf}") + new_hostprefix = f"HostPrefix=../../{desktop_arch_dir}" + new_targetprefix = "Prefix={}".format(str(Path(base_dir).joinpath(qt_version, arch_dir, "target"))) + new_hostdata = "HostData=../{}".format(arch_dir) + new_host_lib_execs = "./bin" if os_name.startswith("windows") else "./libexec" + old_host_lib_execs = re.compile(r"^HostLibraryExecutables=[^\n]*$", flags=re.MULTILINE) + + self._patch_textfile(target_qt_conf, old_host_lib_execs, f"HostLibraryExecutables={new_host_lib_execs}") + for unpatched in unpatched_paths(): + self._patch_textfile(target_qt_conf, f"Prefix={unpatched}target", new_targetprefix) + self._patch_textfile(target_qt_conf, "HostPrefix=../../", new_hostprefix) + self._patch_textfile(target_qt_conf, "HostData=target", new_hostdata) + + def patch_qdevice_file(self, base_dir: str, qt_version: str, arch_dir: str, os_name: str): + """Qt 6.4.1+ specific, but it should not hurt anything if `mkspecs/qdevice.pri` does not exist""" + + qdevice = Path(base_dir) / qt_version / arch_dir / "mkspecs/qdevice.pri" + if not qdevice.exists(): + return + + old_line = re.compile(r"^DEFAULT_ANDROID_NDK_HOST =[^\n]*$", flags=re.MULTILINE) + new_line = f"DEFAULT_ANDROID_NDK_HOST = {'darwin' if os_name == 'mac' else os_name}-x86_64" + self._patch_textfile(qdevice, old_line, new_line) + + @classmethod + def update(cls, target: TargetConfig, base_path: Path, installed_desktop_arch_dir: Optional[str]): + """ + Make Qt configuration files, qt.conf and qtconfig.pri. + And update pkgconfig and patch Qt5Core and qmake + + :param installed_desktop_arch_dir: This is the path to a desktop Qt installation, like `Qt/6.3.0/mingw_win64`. + This may or may not contain an actual desktop Qt installation. + If it does not, the Updater will patch files in a mobile Qt installation + that point to this directory, and this installation will be non-functional + until the user installs a desktop Qt in this directory. + """ + logger = getLogger("aqt.updater") + arch = target.arch + version = Version(target.version) + os_name = target.os_name + version_dir = dir_for_version(version) + arch_dir = QtRepoProperty.get_arch_dir_name(os_name, arch, version) + base_dir = str(base_path) + try: + prefix = base_path / version_dir / arch_dir + updater = Updater(prefix, logger) + updater.set_license(base_dir, version_dir, arch_dir) + if target.arch not in [ + "ios", + "android", + "wasm_32", + "wasm_singlethread", + "wasm_multithread", + "android_x86_64", + "android_arm64_v8a", + "android_x86", + "android_armv7", + "win64_msvc2019_arm64", + "win64_msvc2022_arm64_cross_compiled", + ]: # desktop version + updater.make_qtconf(base_dir, version_dir, arch_dir) + updater.patch_qmake() + if target.os_name == "linux": + updater.patch_pkgconfig("/home/qt/work/install", target.os_name) + updater.patch_libtool("/home/qt/work/install/lib", target.os_name) + updater.patch_prl("/home/qt/work/install/lib") + elif target.os_name == "mac": + updater.patch_pkgconfig("/Users/qt/work/install", target.os_name) + updater.patch_libtool("/Users/qt/work/install/lib", target.os_name) + updater.patch_prl("/Users/qt/work/install/lib") + elif target.os_name.startswith("windows"): + updater.patch_pkgconfig("c:/Users/qt/work/install", target.os_name) + updater.patch_prl("c:/Users/qt/work/install/lib") + updater.make_qtenv2(base_dir, version_dir, arch_dir) + if version < Version("5.14.0"): + updater.patch_qtcore(target) + elif version in SimpleSpec(">=5.0,<6.0"): + updater.patch_qmake() + else: # qt6 mobile, wasm, or msvc-arm64 + if installed_desktop_arch_dir is not None: + desktop_arch_dir = installed_desktop_arch_dir + else: + # Use MetadataFactory to check what the default architecture should be + meta = MetadataFactory(ArchiveId("qt", os_name, "desktop")) + desktop_arch_dir = meta.fetch_default_desktop_arch(version, is_msvc="msvc" in target.arch) + + updater.patch_qt_scripts(base_dir, version_dir, target.os_name, desktop_arch_dir, version) + updater.patch_target_qt_conf(base_dir, version_dir, arch_dir, target.os_name, desktop_arch_dir) + updater.patch_qdevice_file(base_dir, version_dir, arch_dir, target.os_name) + except IOError as e: + raise UpdaterError(f"Updater caused an IO error: {e}") from e + + @classmethod + def patch_kde(cls, src_dir): + logger = logging.getLogger("aqt") + PATCH_URL_BASE = "https://raw.githubusercontent.com/miurahr/kde-qt-patch/main/patches/" + for p in Settings.kde_patches: + logger.info("Apply patch: " + p) + patchfile = patch.fromurl(PATCH_URL_BASE + p) + patchfile.apply(strip=True, root=os.path.join(src_dir, "qtbase")) diff --git a/python/py313/Lib/site-packages/aqt/version.py b/python/py313/Lib/site-packages/aqt/version.py new file mode 100644 index 0000000000000000000000000000000000000000..88c513ea368fba2edc065ecbe625b2a5acf03aa5 --- /dev/null +++ b/python/py313/Lib/site-packages/aqt/version.py @@ -0,0 +1 @@ +__version__ = "3.3.0" diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/INSTALLER b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/METADATA b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..35aaedd83f2fd0b32c851d0d4db5fecb999c1c78 --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/METADATA @@ -0,0 +1,290 @@ +Metadata-Version: 2.4 +Name: aqtinstall +Version: 3.3.0 +Summary: Another unofficial Qt installer +Author-email: Hiroshi Miura +License: MIT License +Project-URL: Documentation, https://aqtinstall.readthedocs.io/ +Project-URL: Bug Tracker, https://github.com/miurahr/aqtinstall/issues +Project-URL: Wiki, https://github.com/miurahr/aqtinstall/wiki +Project-URL: Source, https://github.com/miurahr/aqtinstall +Project-URL: Changelog, https://aqtinstall.readthedocs.io/en/latest/CHANGELOG.html +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Environment :: X11 Applications :: Qt +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: Python +Classifier: Programming Language :: C++ +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: bs4 +Requires-Dist: defusedxml +Requires-Dist: humanize +Requires-Dist: patch-ng +Requires-Dist: py7zr>=0.22.0 +Requires-Dist: requests>=2.31.0 +Requires-Dist: semantic-version +Requires-Dist: texttable +Provides-Extra: test +Requires-Dist: pytest>=6.0; extra == "test" +Requires-Dist: pytest-pep8; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: pytest-remotedata>=0.4.1; extra == "test" +Requires-Dist: pytest-socket; extra == "test" +Requires-Dist: pytest-timeout; extra == "test" +Requires-Dist: pympler; extra == "test" +Provides-Extra: check +Requires-Dist: mypy>=1.10.0; extra == "check" +Requires-Dist: flake8<8.0.0,>=6.0.0; extra == "check" +Requires-Dist: flake8-black; extra == "check" +Requires-Dist: flake8-colors; extra == "check" +Requires-Dist: flake8-isort<7.0.0,>=6.0.0; extra == "check" +Requires-Dist: flake8-pyi; extra == "check" +Requires-Dist: flake8-typing-imports; extra == "check" +Requires-Dist: docutils; extra == "check" +Requires-Dist: check-manifest; extra == "check" +Requires-Dist: readme-renderer; extra == "check" +Requires-Dist: pygments; extra == "check" +Requires-Dist: packaging; extra == "check" +Requires-Dist: pylint; extra == "check" +Requires-Dist: types-requests; extra == "check" +Provides-Extra: docs +Requires-Dist: sphinx>=7.0; extra == "docs" +Requires-Dist: sphinx_rtd_theme>=1.3; extra == "docs" +Requires-Dist: sphinx-py3doc-enhanced-theme>=2.4; extra == "docs" +Provides-Extra: debug +Requires-Dist: pytest-leaks; extra == "debug" +Dynamic: license-file + +Another Qt installer(aqt) +========================= + +- Release: |pypi| +- Documentation: |docs| +- Test status: |gha| and Coverage: |coveralls| +- Code Quality: |codacy| +- Project maturity |Package health| + +.. |pypi| image:: https://badge.fury.io/py/aqtinstall.svg + :target: http://badge.fury.io/py/aqtinstall +.. |docs| image:: https://readthedocs.org/projects/aqtinstall/badge/?version=stable + :target: https://aqtinstall.readthedocs.io/en/latest/?badge=stable +.. |gha| image:: https://github.com/miurahr/aqtinstall/workflows/Test%20on%20GH%20actions%20environment/badge.svg + :target: https://github.com/miurahr/aqtinstall/actions?query=workflow%3A%22Test+on+GH+actions+environment%22 +.. |coveralls| image:: https://coveralls.io/repos/github/miurahr/aqtinstall/badge.svg?branch=master + :target: https://coveralls.io/github/miurahr/aqtinstall?branch=master +.. |Package health| image:: https://snyk.io/advisor/python/aqtinstall/badge.svg + :target: https://snyk.io/advisor/python/aqtinstall + :alt: aqtinstall +.. |codacy| image:: https://app.codacy.com/project/badge/Grade/188accbe7f8f406abf61b888773bf5e3 + :target: https://app.codacy.com/gh/miurahr/aqtinstall/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade + + +This is a utility alternative to the official graphical Qt installer, for using in CI environment +where an interactive UI is not usable, or just on command line. + +It can automatically download prebuilt Qt binaries, documents and sources for target specified, +when the versions are on Qt download mirror sites. + +.. note:: + Because it is an installer utility, it can download from Qt distribution site and its mirror. + The site is operated by The Qt Company who may remove versions you may want to use that become end of support. + Please don't blame us. + +.. warning:: + This is NOT franchised with The Qt Company and The Qt Project. Please don't ask them about aqtinstall. + + +License and copyright +--------------------- + +This program is distributed under MIT license. + +Qt SDK and its related files are under its licenses. When using aqtinstall, you are considered +to agree upon Qt licenses. **aqtinstall installs Qt SDK as of a (L)GPL Free Software.** + +For details see `Qt Licensing`_ and `Licenses used in Qt6`_ + +.. _`Qt Licensing`: https://doc.qt.io/qt-6/licensing.html + +.. _`Licenses used in Qt6`: https://doc.qt.io/qt-6/licenses-used-in-qt.html + +Requirements +------------ + +- Minimum Python version: + 3.9 + +- Recommended Python version: + 3.13 (frequently tested on) + +- Dependencies: + requests + semantic_version + patch + py7zr + texttable + bs4 + defusedxml + +- Operating Systems: + Linux, macOS, MS Windows + + +Documentation +------------- + +There is precise documentation with many examples. +You are recommended to read the *Getting started* section. + +- Getting started: https://aqtinstall.readthedocs.io/en/latest/getting_started.html +- Stable: https://aqtinstall.readthedocs.io/en/stable +- Latest: https://aqtinstall.readthedocs.io/en/latest + +Install +------- + +Same as usual, it can be installed with ``pip``: + +.. code-block:: console + + pip install -U pip + pip install aqtinstall + +You are recommended to update pip before installing aqtinstall. + +.. note:: + + aqtinstall depends several packages, that is required to download files from internet, and extract 7zip archives, + some of which are precompiled in several platforms. + Older pip does not handle it expectedly(see #230). + +.. note:: + + When you want to use it on MSYS2/Mingw64 environment, you need to set environmental variable + ``export SETUPTOOLS_USE_DISTUTILS=stdlib``, because of setuptools package on mingw wrongly + raise error ``VC6.0 is not supported`` + +.. warning:: + + There is an unrelated package `aqt` in pypi. Please don't confuse with it. + +It may be difficult to set up some Windows systems with the correct version of Python and all of ``aqt``'s dependencies. +To get around this problem, ``aqtinstall`` offers ``aqt.exe``, a Windows executable that contains Python and all required dependencies. +You may access ``aqt.exe`` from the `Releases section`_, under "assets", or via the persistent link to `the continuous build`_ of ``aqt.exe``. + +.. _`Releases section`: https://github.com/miurahr/aqtinstall/releases +.. _`the continuous build`: https://github.com/miurahr/aqtinstall/releases/download/Continuous/aqt.exe + + +Example +-------- + +When installing Qt SDK 6.2.0 for Windows. + +Check the options that can be used with the ``list-qt`` subcommand, and query available architectures: + +.. code-block:: console + + aqt list-qt windows desktop --arch 6.2.0 + +Then you may get candidates: ``win64_mingw81 win64_msvc2019_64 win64_msvc2019_arm64``. You can also query the available modules: + +.. code-block:: console + + aqt list-qt windows desktop --modules 6.2.0 win64_mingw81 + + +When you decide to install Qt SDK version 6.2.0 for mingw v8.1: + +.. code-block:: console + + aqt install-qt windows desktop 6.2.0 win64_mingw81 -m all + +The optional `-m all` argument installs all the modules available for Qt 6.2.0; you can leave it off if you don't want those modules. + +To install Qt 6.2.0 with the modules 'qtcharts' and 'qtnetworking', you can use this command (note that the module names are lowercase): + +.. code-block:: console + + aqt install-qt windows desktop 6.2.0 win64_mingw81 -m qtcharts qtnetworking + +When you want to install Qt for android with required desktop toolsets + +.. code-block:: console + + aqt install-qt linux android 5.13.2 android_armv7 --autodesktop + + +When aqtinstall downloads and installs packages, it updates package configurations +such as prefix directory in ``bin/qt.conf``, and ``bin/qconfig.pri`` +to make it working well with installed directory. + +.. note:: + It is your own task to set some environment variables to fit your platform, such as PATH, QT_PLUGIN_PATH, QML_IMPORT_PATH, and QML2_IMPORT_PATH. aqtinstall will never do it for you, in order not to break the installation of multiple versions. + +.. warning:: + If you are using aqtinstall to install the ios version of Qt, please be aware that + there are compatibility issues between XCode 13+ and versions of Qt less than 6.2.4. + You may use aqtinstall to install older versions of Qt for ios, but the developers of + aqtinstall cannot guarantee that older versions will work on the most recent versions of MacOS. + Aqtinstall is tested for ios on MacOS 12 with Qt 6.2.4 and greater. + All earlier versions of Qt are expected not to function. + +Testimonies +----------- + +Some projects utilize aqtinstall, and there are several articles and discussions + +* GitHub Actions: `install_qt`_ + +* Docker image: `docker aqtinstall`_ + +* Yet another comic reader: `YACReader`_ utilize on Azure-Pipelines + +.. _`install_qt`: https://github.com/jurplel/install-qt-action +.. _`docker aqtinstall`: https://github.com/vslotman/docker-aqtinstall +.. _`pyqt5-tools`: https://github.com/altendky/pyqt5-tools +.. _`YACReader`: https://github.com/YACReader/yacreader + + + +* Contributor Nelson's blog article: `Fast and lightweight headless Qt Installer from Qt Mirrors - aqtinstall`_ + +* Lostdomain.org blog: `Using Azure DevOps Pipelines with Qt`_ + +* Wincak's Weblog: `Using Azure CI for cross-platform Linux and Windows Qt application builds`_ + +* Qt Forum: `Automatic installation for Travis CI (or any other CI)`_ + +* Qt Forum: `Qt silent, unattended install`_ + +* Reddit: `Qt Maintenance tool now requires you to enter your company name`_ + +* Qt Study group presentation: `Another Qt CLI installer`_ + + +.. _`Fast and lightweight headless Qt Installer from Qt Mirrors - aqtinstall`: https://mindflakes.com/posts/2019/06/02/fast-and-lightweight-headless-qt-installer-from-qt-mirrors-aqtinstall/ +.. _`Using Azure DevOps Pipelines with Qt`: https://lostdomain.org/2019/12/27/using-azure-devops-pipelines-with-qt/ +.. _`Using Azure CI for cross-platform Linux and Windows Qt application builds`: https://www.wincak.name/programming/using-azure-ci-for-cross-platform-linux-and-windows-qt-application-builds/ +.. _`Automatic installation for Travis CI (or any other CI)`: https://forum.qt.io/topic/114520/automatic-installation-for-travis-ci-or-any-other-ci/2 +.. _`Qt silent, unattended install`: https://forum.qt.io/topic/122185/qt-silent-unattended-install +.. _`Qt Maintenance tool now requires you to enter your company name`: https://www.reddit.com/r/QtFramework/comments/grgrux/qt_maintenance_tool_now_requires_you_to_enter/ +.. _`Another Qt CLI installer`: https://www.slideshare.net/miurahr-nttdata/aqt-install-for-qt-tokyo-r-2-20196 + + +History +------- + +This program is originally shown in Kaidan project as a name `qli-installer`_. +The ``aqtinstall`` project extend and improve it. + +.. _`qli-installer`: https://lnj.gitlab.io/post/qli-installer diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/RECORD b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5c56eb55686af08878cdf5732e996626e4f75453 --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/RECORD @@ -0,0 +1,31 @@ +../../Scripts/aqt.exe,sha256=-cbBVY7-S1tfEASKpHBWKxYzARv4FIHZAT7m6aQB1G8,108340 +aqt/__init__.py,sha256=cb2tw0mJeIB18pjiLmO8JxEg1TSkfW7RieVKuYpe8pw,1581 +aqt/__main__.py,sha256=lceeL2HiWgelq5ERS5UcIudhMXsXCAJUggDqE6AlnUI,1220 +aqt/__pycache__/__init__.cpython-313.pyc,, +aqt/__pycache__/__main__.cpython-313.pyc,, +aqt/__pycache__/archives.cpython-313.pyc,, +aqt/__pycache__/commercial.cpython-313.pyc,, +aqt/__pycache__/exceptions.cpython-313.pyc,, +aqt/__pycache__/helper.cpython-313.pyc,, +aqt/__pycache__/installer.cpython-313.pyc,, +aqt/__pycache__/metadata.cpython-313.pyc,, +aqt/__pycache__/updater.cpython-313.pyc,, +aqt/__pycache__/version.cpython-313.pyc,, +aqt/archives.py,sha256=2f2A_FqGbdUUnJBokzcR8y_x_297roiT0_SjKiR2TkE,29511 +aqt/commercial.py,sha256=gL9ElyjWz-4rczBhutf1ERDqMOXO2772vECNnnzIhmI,15878 +aqt/exceptions.py,sha256=yvwQNHvEOvoBcZKLqwDEGSMBjZ_v3nM42nBkWNTY2pQ,3593 +aqt/helper.py,sha256=R2Eq5HE9_UXn5mBIiaCcnHGBvHR3GmXKRwVLoUHCW9w,30838 +aqt/installer.py,sha256=-2EQauhkvzpBntVvfkYGAQbG-C1zSLwMbSCyBp0q7_A,72628 +aqt/logging.ini,sha256=uXgPjK-PPDhWtlGYoX-HYiJsgCYl0Nym0yo71mwG5KQ,1210 +aqt/metadata.py,sha256=OTaw2YgNtaUUxyuO84DOGQJVwO8WTlJCantjKJCshME,52353 +aqt/settings.ini,sha256=lWsfChZyuQXnRgDRNJpbc2C-HTfXkJ5hzC1xebdyWq0,13580 +aqt/updater.py,sha256=QhBG8kag3uL3Q-KaGLqbvSwS-SaK9GwLBsZIh9gN2is,16166 +aqt/version.py,sha256=MPSbkJS_-QSkLK7sMlFXFf5iWlbcSL18Dj2ZiMCtS9c,22 +aqtinstall-3.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aqtinstall-3.3.0.dist-info/METADATA,sha256=UDliBF431cstE24cCtu2Dq1FlYrtYqJwzYADk3A1Zqo,11472 +aqtinstall-3.3.0.dist-info/RECORD,, +aqtinstall-3.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aqtinstall-3.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +aqtinstall-3.3.0.dist-info/entry_points.txt,sha256=-rWPqTLjP7z-AclECuPwKqb9N8woXXBTrMGXtyoRkPo,42 +aqtinstall-3.3.0.dist-info/licenses/LICENSE,sha256=aMVou9OYVzJLuLtzbIK562O0TVJZf3az8YBDhObyTGw,1141 +aqtinstall-3.3.0.dist-info/top_level.txt,sha256=4ZbCrra52FYe2xDXU7vB2Svv_pFdR-swV4VwN5Hhl-4,4 diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/REQUESTED b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/WHEEL b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/entry_points.txt b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..561280ef0014baab87617e024fe78712a1c0cba2 --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +aqt = aqt.__main__:main diff --git a/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/top_level.txt b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5eb984d391f8ca9cddd57ec46a9f90ca51f223e --- /dev/null +++ b/python/py313/Lib/site-packages/aqtinstall-3.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +aqt diff --git a/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/INSTALLER b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/METADATA b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fb2a2f284963d758c0115b5f5b96b701e0e937ba --- /dev/null +++ b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/METADATA @@ -0,0 +1,216 @@ +Metadata-Version: 2.4 +Name: backports.zstd +Version: 1.5.0 +Summary: Backport of compression.zstd +Author-email: Rogdham +License-Expression: PSF-2.0 +Project-URL: Homepage, https://github.com/rogdham/backports.zstd +Project-URL: Source, https://github.com/rogdham/backports.zstd +Keywords: backport,backports,pep-784,zstd +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Topic :: System :: Archiving :: Compression +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Requires-Python: <3.14,>=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +License-File: LICENSE_zstd.txt +Dynamic: license-file + +
+ +# backports.zstd + +Backport of [PEP-784 “adding Zstandard to the standard library”][PEP-784] + +[![GitHub build status](https://img.shields.io/github/actions/workflow/status/rogdham/backports.zstd/build.yml?branch=master)](https://github.com/rogdham/backports.zstd/actions?query=branch:master) +[![Release on PyPI](https://img.shields.io/pypi/v/backports.zstd)](https://pypi.org/project/backports.zstd/) + +--- + +[📖 PEP-784][PEP-784]   |   [📃 Changelog](./CHANGELOG.md) + +[PEP-784]: https://peps.python.org/pep-0784/ + +
+ +--- + +## Install + +Add the following dependency to your project: + +``` +backports.zstd ; python_version<'3.14' +``` + +…or just run `pip install backports.zstd`. + +## Usage + +When importing a module needing Zstandard support, use a conditional import based on the +version of Python. See below for examples. + +### zstd + +```python +import sys + +if sys.version_info >= (3, 14): + from compression import zstd +else: + from backports import zstd + + +# use the zstd module, for example: +zstd.compress(b"Hello, world!") +``` + +Refer to the [official Python documentation][doc-zstd] for usage of the module. + +[doc-zstd]: https://docs.python.org/3.14/library/compression.zstd.html + +### tarfile + +```python +import sys + +if sys.version_info >= (3, 14): + import tarfile +else: + from backports.zstd import tarfile + + +# use the tarfile module, for example: +with tarfile.open("archive.tar.zst") as tar: + tar.list() +``` + +This `tarfile` modules is backported from Python 3.14 and includes Zstandard-specific +features such as: explicit modes for opening files (e.g. `r:zstd`), specific arguments +(e.g. `zstd_dict`)… refer to the [official Python documentation][doc-tarfile] for more +info. + +[doc-tarfile]: https://docs.python.org/3.14/library/tarfile.html + +Moreover, the CLI is available as well: `python -m backports.zstd.tarfile`. + +### zipfile + +```python +import sys + +if sys.version_info >= (3, 14): + import zipfile +else: + from backports.zstd import zipfile + + +# use the zipfile module, for example: +with zipfile.ZipFile("archive.zip", "w") as zf: + zf.writestr("hello.txt", "Hi!", zipfile.ZIP_ZSTANDARD) +``` + +This `zipfile` modules is backported from Python 3.14 and includes Zstandard-specific +features such as the constant `ZIP_ZSTANDARD` to be used for `compress_type`… refer to +the [official Python documentation][doc-zipfile] for more info. + +[doc-zipfile]: https://docs.python.org/3.14/library/zipfile.html + +Moreover, the CLI is available as well: `python -m backports.zstd.zipfile`. + +### shutil + +```python +import shutil +import sys + +if sys.version_info < (3, 14): + from backports.zstd import register_shutil + register_shutil() + +# use the shutil module, for example +shutil.unpack_archive('archive.tar.zst') +``` + +Calling the `register_shutil` function allows to create zstd'ed tar files using the +`"zstdtar"` format, as well as unpack them. + +It also overrides support for unpacking zip files, enabling the unpacking of zip +archives that use Zstandard for compression. + +Alternatively, call `register_shutil(tar=False)` or `register_shutil(zip=False)` to +choose which archiving support to register. + +## FAQ + +### Who are you? + +This project is created and maintained by [Rogdham](https://github.com/rogdham) +(maintainer of [`pyzstd`](https://github.com/rogdham/pyzstd), who helped with [PEP-784] +and integration of Zstandard into the standard library), with help from +[Emma Smith](https://github.com/emmatyping) (author of [PEP-784], who did most of the +work of porting `pyzstd` into the standard library). + +### How is this backport constructed? + +The aim is to be as close as possible to the upstream code of +[CPython](https://github.com/python/cpython). + +The runtime code comes from CPython 3.14, with minor changes to support older versions +of Python. For PyPy users, the C code has been ported to CFFI. + +During the build phase, the project uses [`zstd`](https://github.com/facebook/zstd) +(canonical implementation of Zstandard) as well as +[`pythoncapi-compat`](https://github.com/python/pythoncapi-compat) (which handles some +of the compatibility with older Python versions). + +Tests come from CPython 3.14, with minor changes to support older versions of Python. +Additional tests have been written specifically for `backports.zstd`. + +The type hints for the standard library have been contributed to +[`typeshed`](https://github.com/python/typeshed) and also backported to +`backports.zstd`. + +### Why can this library not be installed with Python 3.14? + +This is [on purpose](https://github.com/Rogdham/backports.zstd/issues/50). For Python +3.14 and later, use the `compression.zstd` module from the standard library. + +If you want your code to be compatible with multiple Python versions, condition the +usage of this library based on the Python version: + +- [During install](#install); +- [When importing at runtime](#usage). + +### Can I use the libzstd version installed on my system? + +The wheels distributed on PyPI include a static version of `libzstd` for ease of +installation and reproducibility. + +If you want to use `libzstd` installed on your system, pass the `--system-zstd` argument +to the build backend. For example: + +```sh +python -m pip install --config-settings=--build-option=--system-zstd ... +python -m build --wheel --config-setting=--build-option=--system-zstd ... +``` + +If you run the test suite, set the environment variable +`BACKPORTSZSTD_SKIP_EXTENSION_TEST=1` to skip tests that may fail when using the system +library. + +### I found a bug + +If you encounter any issues, please open a +[GitHub issue](https://github.com/Rogdham/backports.zstd/issues/new) with a minimal +reproducible example. + +We will check if the issue is with `backports.zstd` or CPython. We have already reported +and fixed a few issues in CPython this way! diff --git a/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/RECORD b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..14571f206c21aea34f3299b35d411b231905090b --- /dev/null +++ b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/RECORD @@ -0,0 +1,50 @@ +backports/zstd/__init__.py,sha256=2iCNo6g7ZVOZuTlQuo0ewjey2ZGx-g6TGMI4s9rGQ9Y,9328 +backports/zstd/__init__.pyi,sha256=x5flabz3W08WQk6tzFAwITWCVWbU73uVvC2XVmP9x-o,8257 +backports/zstd/__pycache__/__init__.cpython-313.pyc,, +backports/zstd/__pycache__/_compat.cpython-313.pyc,, +backports/zstd/__pycache__/_shutil.cpython-313.pyc,, +backports/zstd/__pycache__/_streams.cpython-313.pyc,, +backports/zstd/__pycache__/_zstd.cpython-313.pyc,, +backports/zstd/__pycache__/_zstdfile.cpython-313.pyc,, +backports/zstd/__pycache__/tarfile.cpython-313.pyc,, +backports/zstd/_cffi/__init__.py,sha256=JUi0NOFda-S3t0pDBTY5CUEHksMe1QvKMTrtGFLcNl8,8190 +backports/zstd/_cffi/__pycache__/__init__.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/_blocks_output_buffer.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/_common.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/buffer.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/compressor.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/decompressor.cpython-313.pyc,, +backports/zstd/_cffi/__pycache__/zstddict.cpython-313.pyc,, +backports/zstd/_cffi/_blocks_output_buffer.py,sha256=Rmn70vPTg2GNEdvi2QKYPSsFCdhT_OyNp5u86mNpebo,3403 +backports/zstd/_cffi/_common.py,sha256=ka4zctVtUyWqoqxIBxLLInUqiCEOG2AuW2W-6LR9-pc,4866 +backports/zstd/_cffi/buffer.py,sha256=EU9EerxO1qYcROrU6Cchy4dCfRtdYkLWRvNhZqU5VSw,797 +backports/zstd/_cffi/compressor.py,sha256=clrbW-HC_i190HD81b7O9OUKvYg5fBRdKA8RtqbSo9s,13635 +backports/zstd/_cffi/decompressor.py,sha256=a-0X8aoHAWjwYW0JWbUpLmOEcQPal6tis7ZeOz3NGRQ,13230 +backports/zstd/_cffi/zstddict.py,sha256=nMb9aSC_Nz0qQx50yFIAAkhrZ6Y5J108aBdMbqBbmJs,6288 +backports/zstd/_compat.py,sha256=NTvC5dwiMfLZJF8Di0NeJ765nEqsBE31vNTzBdA8cbM,2682 +backports/zstd/_shutil.py,sha256=rlFOZoEl13_1H7aP2MtbQg5-DgZ4OFFlHoJdxFzHZXY,4903 +backports/zstd/_streams.py,sha256=i46UOBXHSNAw5UCgI0AMuH-xP3XC8GFaY-xC758VbJI,5670 +backports/zstd/_zstd.cp313-win_amd64.pyd,sha256=xnJ26dxIshOnOu38GPoiuOAw8eljUyGkg8NxtPt0YZo,582144 +backports/zstd/_zstd.py,sha256=YxW09D9QPnZgzRmqVIDcIkGC01oTlCGOpD0tCoCZ9tU,1039 +backports/zstd/_zstdfile.py,sha256=NrvrWVrdAy7WbReZ8NIB5vQqr1G7Ck0VgDVQcXm1SHc,12296 +backports/zstd/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +backports/zstd/tarfile.py,sha256=oN6qru-9GyxCaItKSkGks92s3yoQ_J4DooFcNMrg6yM,118076 +backports/zstd/tarfile.pyi,sha256=JxmS3vz9pUzU6Rsy7b2xSgOZMGvMl1xFbSNtAJIHXIY,27836 +backports/zstd/zipfile/__init__.py,sha256=iNK65tEjOSycOJUcZAXDxf5FWzb3JnsW3jvQHmPd79c,92853 +backports/zstd/zipfile/__init__.pyi,sha256=mLhU8KG0bYdFl_3vN30d3jF0FML_SOTbruFTF5uXinY,8777 +backports/zstd/zipfile/__main__.py,sha256=5BjNuyet8AY-POwoF5rGt722rHQ7tJ0Vf0UFUfzzi-I,58 +backports/zstd/zipfile/__pycache__/__init__.cpython-313.pyc,, +backports/zstd/zipfile/__pycache__/__main__.cpython-313.pyc,, +backports/zstd/zipfile/_path/__init__.py,sha256=ClCtgJbX21snmJCTMdVtN5krzHra9UYiQ7N7sd_HsLA,11973 +backports/zstd/zipfile/_path/__init__.pyi,sha256=wxw3UwdzWQLNE1Vx-HsJ3VDgnBeE2wfHluYdtLc0w_U,2715 +backports/zstd/zipfile/_path/__pycache__/__init__.cpython-313.pyc,, +backports/zstd/zipfile/_path/__pycache__/glob.cpython-313.pyc,, +backports/zstd/zipfile/_path/glob.py,sha256=7e_qY48lC54BFSYUHYOyIqBkZqaONXtteAqLQXPYAvc,3314 +backports/zstd/zipfile/_path/glob.pyi,sha256=6PXA7uH5307e7sWPOHy50m1VqGA82yVzaoDJJkgHH40,671 +backports_zstd-1.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +backports_zstd-1.5.0.dist-info/METADATA,sha256=TSgRjK0dao04YOLPt5puJJ3wUOTNSQtZoS0MNgr7IpU,7036 +backports_zstd-1.5.0.dist-info/RECORD,, +backports_zstd-1.5.0.dist-info/WHEEL,sha256=x5Wpw_tLx5PQKiWdxpqvs0e7Sg-SO0mTWdEADYDGPGA,101 +backports_zstd-1.5.0.dist-info/licenses/LICENSE.txt,sha256=sOJaeM_7Q_TZLei2HM-h8fmOy8IjMLVLUlHntroBAjE,13804 +backports_zstd-1.5.0.dist-info/licenses/LICENSE_zstd.txt,sha256=g2y9qXL3QmGhK3Bq2qfHPa6lNuqWQMmg3Ld7aBBb4FE,1761 +backports_zstd-1.5.0.dist-info/top_level.txt,sha256=cGjaLMOoBR1FK0ApojtzWVmViTtJ7JGIK_HwXiEsvtU,10 diff --git a/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/WHEEL b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f787649e12bd5d319b7ec43d32cec8d136ef81e5 --- /dev/null +++ b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp313-cp313-win_amd64 + diff --git a/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/top_level.txt b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..99d2be5b64d7dc414f8ab9c002de06456b4bada2 --- /dev/null +++ b/python/py313/Lib/site-packages/backports_zstd-1.5.0.dist-info/top_level.txt @@ -0,0 +1 @@ +backports diff --git a/python/py313/Lib/site-packages/bcj/__init__.py b/python/py313/Lib/site-packages/bcj/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf2934cdfd557e5ce5366a0cd16280e814c6fd0e --- /dev/null +++ b/python/py313/Lib/site-packages/bcj/__init__.py @@ -0,0 +1,74 @@ +# PyBcj library. +# Copyright 2020-2022 Hiroshi Miura +# SPDX-License-Identifier: LGPL-2.1-or-later +# +try: + from importlib.metadata import PackageNotFoundError # type: ignore + from importlib.metadata import version # type: ignore +except ImportError: + from importlib_metadata import PackageNotFoundError # type: ignore + from importlib_metadata import version # type: ignore +try: + from ._bcj import ( + ARMDecoder, + ARMEncoder, + ARMTDecoder, + ARMTEncoder, + BCJDecoder, + BCJEncoder, + IA64Decoder, + IA64Encoder, + PPCDecoder, + PPCEncoder, + SparcDecoder, + SparcEncoder, + ) +except ImportError: + try: + from ._bcjfilter import ( + ARMDecoder, + ARMEncoder, + ARMTDecoder, + ARMTEncoder, + BCJDecoder, + BCJEncoder, + IA64Decoder, + IA64Encoder, + PPCDecoder, + PPCEncoder, + SparcDecoder, + SparcEncoder, + ) + except ImportError: + msg = "pybcj module: Neither C implementation nor Python implementation can be imported." + raise ImportError(msg) + +__all__ = ( + ARMDecoder, + ARMEncoder, + ARMTDecoder, + ARMTEncoder, + BCJDecoder, + BCJEncoder, + IA64Decoder, + IA64Encoder, + PPCDecoder, + PPCEncoder, + SparcDecoder, + SparcEncoder, +) + +__copyright__ = "Copyright (C) 2021 Hiroshi Miura" + +try: + __version__ = version(__name__) +except PackageNotFoundError: # pragma: no-cover + # package is not installed + __version__ = "unknown" + +__doc__ = """\ +Python bindings to BCJ filter library. + +Documentation: https://pybcj.readthedocs.io +Github: https://github.com/miurahr/pybcj +PyPI: https://pypi.org/project/pybcj""" diff --git a/python/py313/Lib/site-packages/bcj/_bcj.cp313-win_amd64.pyd b/python/py313/Lib/site-packages/bcj/_bcj.cp313-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c1f10347f3ea7b7f6c7cfe1f573c567406da0380 Binary files /dev/null and b/python/py313/Lib/site-packages/bcj/_bcj.cp313-win_amd64.pyd differ diff --git a/python/py313/Lib/site-packages/bcj/_bcjfilter.py b/python/py313/Lib/site-packages/bcj/_bcjfilter.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9a803a664e3f0b222d000dc96d44c344d81f2c --- /dev/null +++ b/python/py313/Lib/site-packages/bcj/_bcjfilter.py @@ -0,0 +1,264 @@ +# PyBcj library. +# Copyright (c) 2019,2020,2022 Hiroshi Miura +# SPDX-License-Identifier: LGPL-2.1-or-later +# +import struct +from typing import Union + + +class BCJFilter: + + _mask_to_allowed_number = [0, 1, 2, 4, 8, 9, 10, 12] + _mask_to_bit_number = [0, 1, 2, 2, 3, 3, 3, 3] + + def __init__(self, func, readahead: int, is_encoder: bool, stream_size: int = 0): + self.is_encoder: bool = is_encoder + # + self.prev_mask: int = 0 + self.prev_pos: int = -5 + self.current_position: int = 0 + self.stream_size: int = stream_size # should initialize in child class + self.buffer = bytearray() + # + self._method = func + self._readahead = readahead + + def sparc_code(self) -> int: + limit: int = len(self.buffer) - 4 + i: int = 0 + while i <= limit: + if (self.buffer[i], self.buffer[i + 1] & 0xC0) in [ + (0x40, 0x00), + (0x7F, 0xC0), + ]: + src = struct.unpack(">L", self.buffer[i : i + 4])[0] << 2 + distance: int = self.current_position + i + if self.is_encoder: + dest = (src + distance) >> 2 + else: + dest = (src - distance) >> 2 + dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF) | (dest & 0x3FFFFF) | 0x40000000 + self.buffer[i : i + 4] = struct.pack(">L", dest) + i += 4 + self.current_position = i + return i + + def ppc_code(self) -> int: + limit: int = len(self.buffer) - 4 + i: int = 0 + while i <= limit: + # PowerPC branch 6(48) 24(Offset) 1(Abs) 1(Link) + distance: int = self.current_position + i + if self.buffer[i] & 0xFC == 0x48 and self.buffer[i + 3] & 0x03 == 1: + src = struct.unpack(">L", self.buffer[i : i + 4])[0] & 0x3FFFFFC + if self.is_encoder: + dest = src + distance + else: + dest = src - distance + # lsb = int(self.buffer[i + 3]) & 0x03 == 1 + dest = (0x48 << 24) | (dest & 0x03FFFFFF) | 1 + self.buffer[i : i + 4] = struct.pack(">L", dest) + i += 4 + self.current_position = i + return i + + def _unpack_thumb(self, b: Union[bytearray, bytes, memoryview]) -> int: + return ((b[1] & 0x07) << 19) | (b[0] << 11) | ((b[3] & 0x07) << 8) | b[2] + + def _pack_thumb(self, val: int) -> bytes: + b = bytes( + [ + (val >> 11) & 0xFF, + 0xF0 | ((val >> 19) & 0x07), + val & 0xFF, + 0xF8 | ((val >> 8) & 0x07), + ] + ) + return b + + def armt_code(self) -> int: + limit: int = len(self.buffer) - 4 + i: int = 0 + while i <= limit: + if self.buffer[i + 1] & 0xF8 == 0xF0 and self.buffer[i + 3] & 0xF8 == 0xF8: + src = self._unpack_thumb(self.buffer[i : i + 4]) << 1 + distance: int = self.current_position + i + 4 + if self.is_encoder: + dest = src + distance + else: + dest = src - distance + dest >>= 1 + self.buffer[i : i + 4] = self._pack_thumb(dest) + i += 2 + i += 2 + self.current_position += i + return i + + def arm_code(self) -> int: + limit = len(self.buffer) - 4 + i = 0 + while i <= limit: + if self.buffer[i + 3] == 0xEB: + src = struct.unpack("> 2 + else: + dest = (src - distance) >> 2 + self.buffer[i : i + 3] = struct.pack(" int: + """ + The code algorithm from liblzma/simple/x86.c + It is slightly different from LZMA-SDK's bra86.c + :return: buffer position + """ + size: int = len(self.buffer) + if size < 5: + return 0 + if self.current_position - self.prev_pos > 5: + self.prev_pos = self.current_position - 5 + view = memoryview(self.buffer) + limit: int = size - 5 + buffer_pos: int = 0 + pos1: int = 0 + pos2: int = 0 + while buffer_pos <= limit: + # -- + # The following is pythonic way as same as + # if self.buffer[buffer_pos] not in [0xe9, 0xe8]: + # buffer_pos += 1 + # continue + # -- + if pos1 >= 0: + pos1 = self.buffer.find(0xE9, buffer_pos, limit) + if pos2 >= 0: + pos2 = self.buffer.find(0xE8, buffer_pos, limit) + if pos1 < 0 and pos2 < 0: + buffer_pos = limit + 1 + break + elif pos1 < 0: + buffer_pos = pos2 + elif pos2 < 0: + buffer_pos = pos1 + else: + buffer_pos = min(pos1, pos2) + # -- + offset = self.current_position + buffer_pos - self.prev_pos + self.prev_pos = self.current_position + buffer_pos + if offset > 5: + self.prev_mask = 0 + else: + for i in range(offset): + self.prev_mask &= 0x77 + self.prev_mask <<= 1 + # note: + # condition (self.prev_mask >> 1) in [0, 1, 2, 4, 8, 9, 10, 12] + # is as same as + # condition _mask_to_allowed_status[(self.prev_mask >> 1) & 0x7] and (self.prev_mask >> 1) < 0x10: + # when _mask_to_allowed_status = [True, True, True, False, True, False, False, False] + # + if view[buffer_pos + 4] in [0, 0xFF] and (self.prev_mask >> 1) in self._mask_to_allowed_number: + jump_target = self.buffer[buffer_pos + 1 : buffer_pos + 5] + src = struct.unpack("> 1] + while True: + if self.is_encoder: + dest = (src + distance) & 0xFFFFFFFF # uint32 behavior + else: + dest = (src - distance) & 0xFFFFFFFF + if self.prev_mask == 0: + break + b = 0xFF & (dest >> (24 - idx * 8)) + if not (b == 0 or b == 0xFF): + break + src = dest ^ ((1 << (32 - idx * 8)) - 1) & 0xFFFFFFFF + write_view = view[buffer_pos + 1 : buffer_pos + 5] + write_view[0:3] = (dest & 0xFFFFFF).to_bytes(3, "little") + write_view[3:4] = [b"\x00", b"\xff"][(dest >> 24) & 1] # (~(((dest >> 24) & 1) - 1)) & 0xFF + buffer_pos += 5 + self.prev_mask = 0 + else: + buffer_pos += 1 + self.prev_mask |= 1 + if self.buffer[buffer_pos + 3] in [0, 0xFF]: + self.prev_mask |= 0x10 + self.current_position += buffer_pos + return buffer_pos + + def decode(self, data: Union[bytes, bytearray, memoryview], max_length: int = -1) -> bytes: + self.buffer.extend(data) + pos: int = self._method() + if self.current_position > self.stream_size - self._readahead: + offset: int = self.stream_size - self.current_position + tmp = bytes(self.buffer[: pos + offset]) + self.current_position = self.stream_size + self.buffer = bytearray() + else: + tmp = bytes(self.buffer[:pos]) + self.buffer = self.buffer[pos:] + return tmp + + def encode(self, data: Union[bytes, bytearray, memoryview]) -> bytes: + self.buffer.extend(data) + pos: int = self._method() + tmp = bytes(self.buffer[:pos]) + self.buffer = self.buffer[pos:] + return tmp + + def flush(self) -> bytes: + return bytes(self.buffer) + + +class BCJDecoder(BCJFilter): + def __init__(self, size: int): + super().__init__(self.x86_code, 5, False, size) + + +class BCJEncoder(BCJFilter): + def __init__(self): + super().__init__(self.x86_code, 5, True) + + +class SparcDecoder(BCJFilter): + def __init__(self, size: int): + super().__init__(self.sparc_code, 4, False, size) + + +class SparcEncoder(BCJFilter): + def __init__(self): + super().__init__(self.sparc_code, 4, True) + + +class PPCDecoder(BCJFilter): + def __init__(self, size: int): + super().__init__(self.ppc_code, 4, False, size) + + +class PPCEncoder(BCJFilter): + def __init__(self): + super().__init__(self.ppc_code, 4, True) + + +class ARMTDecoder(BCJFilter): + def __init__(self, size: int): + super().__init__(self.armt_code, 4, False, size) + + +class ARMTEncoder(BCJFilter): + def __init__(self): + super().__init__(self.armt_code, 4, True) + + +class ARMDecoder(BCJFilter): + def __init__(self, size: int): + super().__init__(self.arm_code, 4, False, size) + + +class ARMEncoder(BCJFilter): + def __init__(self): + super().__init__(self.arm_code, 4, True) diff --git a/python/py313/Lib/site-packages/bcj/py.typed b/python/py313/Lib/site-packages/bcj/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/INSTALLER b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/METADATA b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7fd97b7693782a2fde21343a55aef0b344c22453 --- /dev/null +++ b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/METADATA @@ -0,0 +1,123 @@ +Metadata-Version: 2.4 +Name: beautifulsoup4 +Version: 4.14.3 +Summary: Screen-scraping library +Project-URL: Download, https://www.crummy.com/software/BeautifulSoup/bs4/download/ +Project-URL: Homepage, https://www.crummy.com/software/BeautifulSoup/bs4/ +Author-email: Leonard Richardson +License: MIT License +License-File: AUTHORS +License-File: LICENSE +Keywords: HTML,XML,parse,soup +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Topic :: Text Processing :: Markup :: SGML +Classifier: Topic :: Text Processing :: Markup :: XML +Requires-Python: >=3.7.0 +Requires-Dist: soupsieve>=1.6.1 +Requires-Dist: typing-extensions>=4.0.0 +Provides-Extra: cchardet +Requires-Dist: cchardet; extra == 'cchardet' +Provides-Extra: chardet +Requires-Dist: chardet; extra == 'chardet' +Provides-Extra: charset-normalizer +Requires-Dist: charset-normalizer; extra == 'charset-normalizer' +Provides-Extra: html5lib +Requires-Dist: html5lib; extra == 'html5lib' +Provides-Extra: lxml +Requires-Dist: lxml; extra == 'lxml' +Description-Content-Type: text/markdown + +Beautiful Soup is a library that makes it easy to scrape information +from web pages. It sits atop an HTML or XML parser, providing Pythonic +idioms for iterating, searching, and modifying the parse tree. + +# Quick start + +``` +>>> from bs4 import BeautifulSoup +>>> soup = BeautifulSoup("

SomebadHTML") +>>> print(soup.prettify()) + + +

+ Some + + bad + + HTML + + +

+ + +>>> soup.find(string="bad") +'bad' +>>> soup.i +HTML +# +>>> soup = BeautifulSoup("SomebadXML", "xml") +# +>>> print(soup.prettify()) + + + Some + + bad + + XML + + +``` + +To go beyond the basics, [comprehensive documentation is available](https://www.crummy.com/software/BeautifulSoup/bs4/doc/). + +# Links + +* [Homepage](https://www.crummy.com/software/BeautifulSoup/bs4/) +* [Documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) +* [Discussion group](https://groups.google.com/group/beautifulsoup/) +* [Development](https://code.launchpad.net/beautifulsoup/) +* [Bug tracker](https://bugs.launchpad.net/beautifulsoup/) +* [Complete changelog](https://git.launchpad.net/beautifulsoup/tree/CHANGELOG) + +# Note on Python 2 sunsetting + +Beautiful Soup's support for Python 2 was discontinued on December 31, +2020: one year after the sunset date for Python 2 itself. From this +point onward, new Beautiful Soup development will exclusively target +Python 3. The final release of Beautiful Soup 4 to support Python 2 +was 4.9.3. + +# Supporting the project + +If you use Beautiful Soup as part of your professional work, please consider a +[Tidelift subscription](https://tidelift.com/subscription/pkg/pypi-beautifulsoup4?utm_source=pypi-beautifulsoup4&utm_medium=referral&utm_campaign=readme). +This will support many of the free software projects your organization +depends on, not just Beautiful Soup. + +If you use Beautiful Soup for personal projects, the best way to say +thank you is to read +[Tool Safety](https://www.crummy.com/software/BeautifulSoup/zine/), a zine I +wrote about what Beautiful Soup has taught me about software +development. + +# Building the documentation + +The bs4/doc/ directory contains full documentation in Sphinx +format. Run `make html` in that directory to create HTML +documentation. + +# Running the unit tests + +Beautiful Soup supports unit test discovery using Pytest: + +``` +$ pytest +``` + diff --git a/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/RECORD b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..def30e2d2a953205c953e158909be8e4a1531fc1 --- /dev/null +++ b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/RECORD @@ -0,0 +1,37 @@ +beautifulsoup4-4.14.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +beautifulsoup4-4.14.3.dist-info/METADATA,sha256=Ac93vA8Xp9FtgOcKXFM8ESfVdztimUfJ3WUpVlhKtsY,3812 +beautifulsoup4-4.14.3.dist-info/RECORD,, +beautifulsoup4-4.14.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +beautifulsoup4-4.14.3.dist-info/licenses/AUTHORS,sha256=uYkjiRjh_aweRnF8tAW2PpJJeickE68NmJwd9siry28,2201 +beautifulsoup4-4.14.3.dist-info/licenses/LICENSE,sha256=VbTY1LHlvIbRDvrJG3TIe8t3UmsPW57a-LnNKtxzl7I,1441 +bs4/__init__.py,sha256=E7wiVp7oQK0JhdAYxpehZa8drv3W_sJv5oeTFiBfR5o,44386 +bs4/__pycache__/__init__.cpython-313.pyc,, +bs4/__pycache__/_deprecation.cpython-313.pyc,, +bs4/__pycache__/_typing.cpython-313.pyc,, +bs4/__pycache__/_warnings.cpython-313.pyc,, +bs4/__pycache__/css.cpython-313.pyc,, +bs4/__pycache__/dammit.cpython-313.pyc,, +bs4/__pycache__/diagnose.cpython-313.pyc,, +bs4/__pycache__/element.cpython-313.pyc,, +bs4/__pycache__/exceptions.cpython-313.pyc,, +bs4/__pycache__/filter.cpython-313.pyc,, +bs4/__pycache__/formatter.cpython-313.pyc,, +bs4/_deprecation.py,sha256=niHJCk37APg8KEuFOa57ZXaxLdBmc_2V6uuaJqu7r30,2408 +bs4/_typing.py,sha256=zNcx7R1yCTK8WwtumP28hc7CJ3pMyZXj_VAeYaNXMZA,7549 +bs4/_warnings.py,sha256=ZuOETgcnEbZgw2N0nnNXn6wvtrn2ut7AF0d98bvkMFc,4711 +bs4/builder/__init__.py,sha256=Rl4qjOXvdyyyjayOFqbkgoUoo81IgoyKD-RwWeVK59g,31194 +bs4/builder/__pycache__/__init__.cpython-313.pyc,, +bs4/builder/__pycache__/_html5lib.cpython-313.pyc,, +bs4/builder/__pycache__/_htmlparser.cpython-313.pyc,, +bs4/builder/__pycache__/_lxml.cpython-313.pyc,, +bs4/builder/_html5lib.py,sha256=hL6xUk4_I2i5CMguFoYFlrI26cY4Dut7fOEQrUctHIM,23607 +bs4/builder/_htmlparser.py,sha256=CnULPQV2rm4vLojJABpQ7Xm9diddnEZx2Wcz_VTC1Mg,17445 +bs4/builder/_lxml.py,sha256=ks1e8boA_nOA2oomAhxeudccR6ThbEE-EllFqHRoPLA,18969 +bs4/css.py,sha256=_m_l_4SGWHnY620VJ21j_qQH1RX3p91sYVemgKxaLsM,12713 +bs4/dammit.py,sha256=ZJWa9K32X6N2imFHleqUq0ekf592weU1lvULN_WYWYk,57024 +bs4/diagnose.py,sha256=at98iuxyOrqec4V8iwkTIbNUqBCsq9Lr3fDAQx2129Y,7846 +bs4/element.py,sha256=oXmj7LG_2NpsDK90mq73q0PMK0FjFBIGSeTTJLVwwTc,120237 +bs4/exceptions.py,sha256=Q9FOadNe8QRvzDMaKSXe2Wtl8JK_oAZW7mbFZBVP_GE,951 +bs4/filter.py,sha256=rw8ZNhTDLEJVCEiSifou5tZR_3zBLeuvAyouY82qU_E,29201 +bs4/formatter.py,sha256=uBT0k6W8O5kJ9PCuJYjra97yoUqC-dlM9D_v-oRM0r8,10478 +bs4/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/WHEEL b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/python/py313/Lib/site-packages/beautifulsoup4-4.14.3.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/INSTALLER b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/METADATA b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..91b106d3b6b731ed6a98e9fc9c3d524a0ec5af04 --- /dev/null +++ b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/METADATA @@ -0,0 +1,158 @@ +Metadata-Version: 2.4 +Name: brotli +Version: 1.2.0 +Summary: Python bindings for the Brotli compression library +Home-page: https://github.com/google/brotli +Author: The Brotli Authors +License: MIT +Platform: Posix +Platform: MacOS X +Platform: Windows +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: C +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Unix Shell +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: System :: Archiving +Classifier: Topic :: System :: Archiving :: Compression +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Utilities +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: author +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: summary + +

+ GitHub Actions Build Status + Fuzzing Status +

+

Brotli

+ +### Introduction + +Brotli is a generic-purpose lossless compression algorithm that compresses data +using a combination of a modern variant of the LZ77 algorithm, Huffman coding +and 2nd order context modeling, with a compression ratio comparable to the best +currently available general-purpose compression methods. It is similar in speed +with deflate but offers more dense compression. + +The specification of the Brotli Compressed Data Format is defined in +[RFC 7932](https://datatracker.ietf.org/doc/html/rfc7932). + +Brotli is open-sourced under the MIT License, see the LICENSE file. + +> **Please note:** brotli is a "stream" format; it does not contain +> meta-information, like checksums or uncompressed data length. It is possible +> to modify "raw" ranges of the compressed stream and the decoder will not +> notice that. + +### Installation + +In most Linux distributions, installing `brotli` is just a matter of using +the package management system. For example in Debian-based distributions: +`apt install brotli` will install `brotli`. On MacOS, you can use +[Homebrew](https://brew.sh/): `brew install brotli`. + +[![brotli packaging status](https://repology.org/badge/vertical-allrepos/brotli.svg?exclude_unsupported=1&columns=3&exclude_sources=modules,site&header=brotli%20packaging%20status)](https://repology.org/project/brotli/versions) + +Of course you can also build brotli from sources. + +### Build instructions + +#### Vcpkg + +You can download and install brotli using the +[vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager: + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + ./vcpkg install brotli + +The brotli port in vcpkg is kept up to date by Microsoft team members and +community contributors. If the version is out of date, please [create an issue +or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + +#### Bazel + +See [Bazel](https://www.bazel.build/) + +#### CMake + +The basic commands to build and install brotli are: + + $ mkdir out && cd out + $ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./installed .. + $ cmake --build . --config Release --target install + +You can use other [CMake](https://cmake.org/) configuration. + +#### Python + +To install the latest release of the Python module, run the following: + + $ pip install brotli + +To install the tip-of-the-tree version, run: + + $ pip install --upgrade git+https://github.com/google/brotli + +See the [Python readme](python/README.md) for more details on installing +from source, development, and testing. + +### Contributing + +We glad to answer/library related questions in +[brotli mailing list](https://groups.google.com/g/brotli). + +Regular issues / feature requests should be reported in +[issue tracker](https://github.com/google/brotli/issues). + +For reporting vulnerability please read [SECURITY](SECURITY.md). + +For contributing changes please read [CONTRIBUTING](CONTRIBUTING.md). + +### Benchmarks +* [Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/) / [Unstable Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/unstable/) +* [Large Text Compression Benchmark](https://mattmahoney.net/dc/text.html) +* [Lzturbo Benchmark](https://sites.google.com/site/powturbo/home/benchmark) + +### Related projects +> **Disclaimer:** Brotli authors take no responsibility for the third party projects mentioned in this section. + +Independent [decoder](https://github.com/madler/brotli) implementation +by Mark Adler, based entirely on format specification. + +JavaScript port of brotli [decoder](https://github.com/devongovett/brotli.js). +Could be used directly via `npm install brotli` + +Hand ported [decoder / encoder](https://github.com/dominikhlbg/BrotliHaxe) +in haxe by Dominik Homberger. +Output source code: JavaScript, PHP, Python, Java and C# + +7Zip [plugin](https://github.com/mcmilk/7-Zip-Zstd) + +Dart compression framework with +[fast FFI-based Brotli implementation](https://pub.dev/documentation/es_compression/latest/brotli/) +with ready-to-use prebuilt binaries for Win/Linux/Mac diff --git a/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/RECORD b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..66bba03e284dbb80d88ddfcfeea1680a460f2e90 --- /dev/null +++ b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/RECORD @@ -0,0 +1,9 @@ +__pycache__/brotli.cpython-313.pyc,, +_brotli.cp313-win_amd64.pyd,sha256=p_gwhqmZoB2wyoy6bUdrSqdOwvliks9OF0Rt0wwIXGE,856576 +brotli-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +brotli-1.2.0.dist-info/METADATA,sha256=dLzObyHAQu_lsd37HPc2cDB_IdeFaA1feDjHkiJvkdE,6274 +brotli-1.2.0.dist-info/RECORD,, +brotli-1.2.0.dist-info/WHEEL,sha256=qV0EIPljj1XC_vuSatRWjn02nZIz3N1t8jsZz7HBr2U,101 +brotli-1.2.0.dist-info/licenses/LICENSE,sha256=YK4PE-dswuqqEIZ37vpM4Wtkf2u-jPChrJQp2C7Kckg,1103 +brotli-1.2.0.dist-info/top_level.txt,sha256=gsS54HrhO3ZveFxeMrKo_7qH4Sm4TbQ7jGLVBEqJ4NI,15 +brotli.py,sha256=_i8MubwH-A-oO0fza84xahZ_OxtujMLp3AEXy0pMxTU,2027 diff --git a/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/WHEEL b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..6d2a2065ef77d1af276d5a84392810cc124b795b --- /dev/null +++ b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-cp313-win_amd64 + diff --git a/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/top_level.txt b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a111e9cca6fb4d3696239f5bb98bee20cb2914e7 --- /dev/null +++ b/python/py313/Lib/site-packages/brotli-1.2.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_brotli +brotli diff --git a/python/py313/Lib/site-packages/brotli.py b/python/py313/Lib/site-packages/brotli.py new file mode 100644 index 0000000000000000000000000000000000000000..271b460620eb9ffda2de684005a0164200f516f1 --- /dev/null +++ b/python/py313/Lib/site-packages/brotli.py @@ -0,0 +1,57 @@ +# Copyright 2016 The Brotli Authors. All rights reserved. +# +# Distributed under MIT license. +# See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + +"""Functions to compress and decompress data using the Brotli library.""" + +import _brotli + +# The library version. +version = __version__ = _brotli.__version__ + +# The compression mode. +MODE_GENERIC = _brotli.MODE_GENERIC +MODE_TEXT = _brotli.MODE_TEXT +MODE_FONT = _brotli.MODE_FONT + +# The Compressor object. +Compressor = _brotli.Compressor + +# The Decompressor object. +Decompressor = _brotli.Decompressor + +# Compress a byte string. +def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0): + """Compress a byte string. + + Args: + string (bytes): The input data. + mode (int, optional): The compression mode; value 0 should be used for + generic input (MODE_GENERIC); value 1 might be beneficial for UTF-8 text + input (MODE_TEXT); value 2 tunes encoder for WOFF 2.0 data (MODE_FONT). + Defaults to 0. + quality (int, optional): Controls the compression-speed vs compression- + density tradeoff. The higher the quality, the slower the compression. + Range is 0 to 11. Defaults to 11. + lgwin (int, optional): Base 2 logarithm of the sliding window size. Range + is 10 to 24. Defaults to 22. + lgblock (int, optional): Base 2 logarithm of the maximum input block size. + Range is 16 to 24. If set to 0, the value will be set based on the + quality. Defaults to 0. + + Returns: + The compressed byte string. + + Raises: + brotli.error: If arguments are invalid, or compressor fails. + """ + compressor = Compressor(mode=mode, quality=quality, lgwin=lgwin, + lgblock=lgblock) + return compressor.process(string) + compressor.finish() + +# Decompress a compressed byte string. +decompress = _brotli.decompress + +# Raised if compression or decompression fails. +error = _brotli.error diff --git a/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/INSTALLER b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/METADATA b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0eaeb1d24ef611bd970c53b653c61c8155e8dee5 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/METADATA @@ -0,0 +1,10 @@ +Metadata-Version: 2.1 +Name: bs4 +Version: 0.0.2 +Summary: Dummy package for Beautiful Soup (beautifulsoup4) +Author-email: Leonard Richardson +License: MIT License +Requires-Dist: beautifulsoup4 +Description-Content-Type: text/x-rst + +This is a dummy package designed to prevent namesquatting on PyPI. You should install `beautifulsoup4 `_ instead. diff --git a/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/RECORD b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..36b77a707d55fa41ae34c7347c09b7898379bf3e --- /dev/null +++ b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/RECORD @@ -0,0 +1,5 @@ +README.rst,sha256=KMs4D-t40JC-oge8vGS3O5gueksurGqAIFxPtHZAMXQ,159 +bs4-0.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +bs4-0.0.2.dist-info/METADATA,sha256=GEwOSFCOYLu11XQR3O2dMO7ZTpKFZpGoIUG0gkFVgA8,411 +bs4-0.0.2.dist-info/RECORD,, +bs4-0.0.2.dist-info/WHEEL,sha256=VYAwk8D_V6zmIA2XKK-k7Fem_KAtVk3hugaRru3yjGc,105 diff --git a/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/WHEEL b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..a5543bae8de8b5636341fae2f789b174140e9865 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4-0.0.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.21.0 +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any diff --git a/python/py313/Lib/site-packages/bs4/__init__.py b/python/py313/Lib/site-packages/bs4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..19b7c0ed057f19b9a32247b5a4eb8eca97ff2f04 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/__init__.py @@ -0,0 +1,1174 @@ +"""Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend". + +http://www.crummy.com/software/BeautifulSoup/ + +Beautiful Soup uses a pluggable XML or HTML parser to parse a +(possibly invalid) document into a tree representation. Beautiful Soup +provides methods and Pythonic idioms that make it easy to navigate, +search, and modify the parse tree. + +Beautiful Soup works with Python 3.7 and up. It works better if lxml +and/or html5lib is installed, but they are not required. + +For more than you ever wanted to know about Beautiful Soup, see the +documentation: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ +""" + +__author__ = "Leonard Richardson (leonardr@segfault.org)" +__version__ = "4.14.3" +__copyright__ = "Copyright (c) 2004-2025 Leonard Richardson" +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +__all__ = [ + "AttributeResemblesVariableWarning", + "BeautifulSoup", + "Comment", + "Declaration", + "ProcessingInstruction", + "ResultSet", + "CSS", + "Script", + "Stylesheet", + "Tag", + "TemplateString", + "ElementFilter", + "UnicodeDammit", + "CData", + "Doctype", + + # Exceptions + "FeatureNotFound", + "ParserRejectedMarkup", + "StopParsing", + + # Warnings + "AttributeResemblesVariableWarning", + "GuessedAtParserWarning", + "MarkupResemblesLocatorWarning", + "UnusualUsageWarning", + "XMLParsedAsHTMLWarning", +] + +from collections import Counter +import io +import sys +import warnings + +# The very first thing we do is give a useful error if someone is +# running this code under Python 2. +if sys.version_info.major < 3: + raise ImportError( + "You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3." + ) + +from .builder import ( + builder_registry, + TreeBuilder, +) +from .builder._htmlparser import HTMLParserTreeBuilder +from .dammit import UnicodeDammit +from .css import CSS +from ._deprecation import ( + _deprecated, +) +from .element import ( + CData, + Comment, + DEFAULT_OUTPUT_ENCODING, + Declaration, + Doctype, + NavigableString, + PageElement, + ProcessingInstruction, + PYTHON_SPECIFIC_ENCODINGS, + ResultSet, + Script, + Stylesheet, + Tag, + TemplateString, +) +from .formatter import Formatter +from .filter import ( + ElementFilter, + SoupStrainer, +) +from typing import ( + Any, + cast, + Counter as CounterType, + Dict, + Iterator, + List, + Sequence, + Sized, + Optional, + Type, + Union, +) + +from bs4._typing import ( + _Encoding, + _Encodings, + _IncomingMarkup, + _InsertableElement, + _RawAttributeValue, + _RawAttributeValues, + _RawMarkup, +) + +# Import all warnings and exceptions into the main package. +from bs4.exceptions import ( + FeatureNotFound, + ParserRejectedMarkup, + StopParsing, +) +from bs4._warnings import ( + AttributeResemblesVariableWarning, + GuessedAtParserWarning, + MarkupResemblesLocatorWarning, + UnusualUsageWarning, + XMLParsedAsHTMLWarning, +) + + +class BeautifulSoup(Tag): + """A data structure representing a parsed HTML or XML document. + + Most of the methods you'll call on a BeautifulSoup object are inherited from + PageElement or Tag. + + Internally, this class defines the basic interface called by the + tree builders when converting an HTML/XML document into a data + structure. The interface abstracts away the differences between + parsers. To write a new tree builder, you'll need to understand + these methods as a whole. + + These methods will be called by the BeautifulSoup constructor: + * reset() + * feed(markup) + + The tree builder may call these methods from its feed() implementation: + * handle_starttag(name, attrs) # See note about return value + * handle_endtag(name) + * handle_data(data) # Appends to the current data node + * endData(containerClass) # Ends the current data node + + No matter how complicated the underlying parser is, you should be + able to build a tree using 'start tag' events, 'end tag' events, + 'data' events, and "done with data" events. + + If you encounter an empty-element tag (aka a self-closing tag, + like HTML's
tag), call handle_starttag and then + handle_endtag. + """ + + #: Since `BeautifulSoup` subclasses `Tag`, it's possible to treat it as + #: a `Tag` with a `Tag.name`. Hoever, this name makes it clear the + #: `BeautifulSoup` object isn't a real markup tag. + ROOT_TAG_NAME: str = "[document]" + + #: If the end-user gives no indication which tree builder they + #: want, look for one with these features. + DEFAULT_BUILDER_FEATURES: Sequence[str] = ["html", "fast"] + + #: A string containing all ASCII whitespace characters, used in + #: during parsing to detect data chunks that seem 'empty'. + ASCII_SPACES: str = "\x20\x0a\x09\x0c\x0d" + + # FUTURE PYTHON: + element_classes: Dict[Type[PageElement], Type[PageElement]] #: :meta private: + builder: TreeBuilder #: :meta private: + is_xml: bool + known_xml: Optional[bool] + parse_only: Optional[SoupStrainer] #: :meta private: + + # These members are only used while parsing markup. + markup: Optional[_RawMarkup] #: :meta private: + current_data: List[str] #: :meta private: + currentTag: Optional[Tag] #: :meta private: + tagStack: List[Tag] #: :meta private: + open_tag_counter: CounterType[str] #: :meta private: + preserve_whitespace_tag_stack: List[Tag] #: :meta private: + string_container_stack: List[Tag] #: :meta private: + _most_recent_element: Optional[PageElement] #: :meta private: + + #: Beautiful Soup's best guess as to the character encoding of the + #: original document. + original_encoding: Optional[_Encoding] + + #: The character encoding, if any, that was explicitly defined + #: in the original document. This may or may not match + #: `BeautifulSoup.original_encoding`. + declared_html_encoding: Optional[_Encoding] + + #: This is True if the markup that was parsed contains + #: U+FFFD REPLACEMENT_CHARACTER characters which were not present + #: in the original markup. These mark character sequences that + #: could not be represented in Unicode. + contains_replacement_characters: bool + + def __init__( + self, + markup: _IncomingMarkup = "", + features: Optional[Union[str, Sequence[str]]] = None, + builder: Optional[Union[TreeBuilder, Type[TreeBuilder]]] = None, + parse_only: Optional[SoupStrainer] = None, + from_encoding: Optional[_Encoding] = None, + exclude_encodings: Optional[_Encodings] = None, + element_classes: Optional[Dict[Type[PageElement], Type[PageElement]]] = None, + **kwargs: Any, + ): + """Constructor. + + :param markup: A string or a file-like object representing + markup to be parsed. + + :param features: Desirable features of the parser to be + used. This may be the name of a specific parser ("lxml", + "lxml-xml", "html.parser", or "html5lib") or it may be the + type of markup to be used ("html", "html5", "xml"). It's + recommended that you name a specific parser, so that + Beautiful Soup gives you the same results across platforms + and virtual environments. + + :param builder: A TreeBuilder subclass to instantiate (or + instance to use) instead of looking one up based on + `features`. You only need to use this if you've implemented a + custom TreeBuilder. + + :param parse_only: A SoupStrainer. Only parts of the document + matching the SoupStrainer will be considered. This is useful + when parsing part of a document that would otherwise be too + large to fit into memory. + + :param from_encoding: A string indicating the encoding of the + document to be parsed. Pass this in if Beautiful Soup is + guessing wrongly about the document's encoding. + + :param exclude_encodings: A list of strings indicating + encodings known to be wrong. Pass this in if you don't know + the document's encoding but you know Beautiful Soup's guess is + wrong. + + :param element_classes: A dictionary mapping BeautifulSoup + classes like Tag and NavigableString, to other classes you'd + like to be instantiated instead as the parse tree is + built. This is useful for subclassing Tag or NavigableString + to modify default behavior. + + :param kwargs: For backwards compatibility purposes, the + constructor accepts certain keyword arguments used in + Beautiful Soup 3. None of these arguments do anything in + Beautiful Soup 4; they will result in a warning and then be + ignored. + + Apart from this, any keyword arguments passed into the + BeautifulSoup constructor are propagated to the TreeBuilder + constructor. This makes it possible to configure a + TreeBuilder by passing in arguments, not just by saying which + one to use. + """ + if "convertEntities" in kwargs: + del kwargs["convertEntities"] + warnings.warn( + "BS4 does not respect the convertEntities argument to the " + "BeautifulSoup constructor. Entities are always converted " + "to Unicode characters." + ) + + if "markupMassage" in kwargs: + del kwargs["markupMassage"] + warnings.warn( + "BS4 does not respect the markupMassage argument to the " + "BeautifulSoup constructor. The tree builder is responsible " + "for any necessary markup massage." + ) + + if "smartQuotesTo" in kwargs: + del kwargs["smartQuotesTo"] + warnings.warn( + "BS4 does not respect the smartQuotesTo argument to the " + "BeautifulSoup constructor. Smart quotes are always converted " + "to Unicode characters." + ) + + if "selfClosingTags" in kwargs: + del kwargs["selfClosingTags"] + warnings.warn( + "Beautiful Soup 4 does not respect the selfClosingTags argument to the " + "BeautifulSoup constructor. The tree builder is responsible " + "for understanding self-closing tags." + ) + + if "isHTML" in kwargs: + del kwargs["isHTML"] + warnings.warn( + "Beautiful Soup 4 does not respect the isHTML argument to the " + "BeautifulSoup constructor. Suggest you use " + "features='lxml' for HTML and features='lxml-xml' for " + "XML." + ) + + def deprecated_argument(old_name: str, new_name: str) -> Optional[Any]: + if old_name in kwargs: + warnings.warn( + 'The "%s" argument to the BeautifulSoup constructor ' + 'was renamed to "%s" in Beautiful Soup 4.0.0' + % (old_name, new_name), + DeprecationWarning, + stacklevel=3, + ) + return kwargs.pop(old_name) + return None + + parse_only = parse_only or deprecated_argument("parseOnlyThese", "parse_only") + if parse_only is not None: + # Issue a warning if we can tell in advance that + # parse_only will exclude the entire tree. + if parse_only.excludes_everything: + warnings.warn( + f"The given value for parse_only will exclude everything: {parse_only}", + UserWarning, + stacklevel=3, + ) + + from_encoding = from_encoding or deprecated_argument( + "fromEncoding", "from_encoding" + ) + + if from_encoding and isinstance(markup, str): + warnings.warn( + "You provided Unicode markup but also provided a value for from_encoding. Your from_encoding will be ignored." + ) + from_encoding = None + + self.element_classes = element_classes or dict() + + # We need this information to track whether or not the builder + # was specified well enough that we can omit the 'you need to + # specify a parser' warning. + original_builder = builder + original_features = features + + builder_class: Optional[Type[TreeBuilder]] = None + if isinstance(builder, type): + # A builder class was passed in; it needs to be instantiated. + builder_class = builder + builder = None + elif builder is None: + if isinstance(features, str): + features = [features] + if features is None or len(features) == 0: + features = self.DEFAULT_BUILDER_FEATURES + possible_builder_class = builder_registry.lookup(*features) + if possible_builder_class is None: + raise FeatureNotFound( + "Couldn't find a tree builder with the features you " + "requested: %s. Do you need to install a parser library?" + % ",".join(features) + ) + builder_class = possible_builder_class + + # At this point either we have a TreeBuilder instance in + # builder, or we have a builder_class that we can instantiate + # with the remaining **kwargs. + if builder is None: + assert builder_class is not None + builder = builder_class(**kwargs) + if ( + not original_builder + and not ( + original_features == builder.NAME + or ( + isinstance(original_features, str) + and original_features in builder.ALTERNATE_NAMES + ) + ) + and markup + ): + # The user did not tell us which TreeBuilder to use, + # and we had to guess. Issue a warning. + if builder.is_xml: + markup_type = "XML" + else: + markup_type = "HTML" + + # This code adapted from warnings.py so that we get the same line + # of code as our warnings.warn() call gets, even if the answer is wrong + # (as it may be in a multithreading situation). + caller = None + try: + caller = sys._getframe(1) + except ValueError: + pass + if caller: + globals = caller.f_globals + line_number = caller.f_lineno + else: + globals = sys.__dict__ + line_number = 1 + filename = globals.get("__file__") + if filename: + fnl = filename.lower() + if fnl.endswith((".pyc", ".pyo")): + filename = filename[:-1] + if filename: + # If there is no filename at all, the user is most likely in a REPL, + # and the warning is not necessary. + values = dict( + filename=filename, + line_number=line_number, + parser=builder.NAME, + markup_type=markup_type, + ) + warnings.warn( + GuessedAtParserWarning.MESSAGE % values, + GuessedAtParserWarning, + stacklevel=2, + ) + else: + if kwargs: + warnings.warn( + "Keyword arguments to the BeautifulSoup constructor will be ignored. These would normally be passed into the TreeBuilder constructor, but a TreeBuilder instance was passed in as `builder`." + ) + + self.builder = builder + self.is_xml = builder.is_xml + self.known_xml = self.is_xml + self._namespaces = dict() + self.parse_only = parse_only + + if hasattr(markup, "read"): # It's a file-type object. + markup = cast(io.IOBase, markup).read() + elif not isinstance(markup, (bytes, str)) and not hasattr(markup, "__len__"): + raise TypeError( + f"Incoming markup is of an invalid type: {markup!r}. Markup must be a string, a bytestring, or an open filehandle." + ) + elif isinstance(markup, Sized) and len(markup) <= 256 and ( + (isinstance(markup, bytes) and b"<" not in markup and b"\n" not in markup) + or (isinstance(markup, str) and "<" not in markup and "\n" not in markup) + ): + # Issue warnings for a couple beginner problems + # involving passing non-markup to Beautiful Soup. + # Beautiful Soup will still parse the input as markup, + # since that is sometimes the intended behavior. + if not self._markup_is_url(markup): + self._markup_resembles_filename(markup) + + # At this point we know markup is a string or bytestring. If + # it was a file-type object, we've read from it. + markup = cast(_RawMarkup, markup) + + rejections = [] + success = False + for ( + self.markup, + self.original_encoding, + self.declared_html_encoding, + self.contains_replacement_characters, + ) in self.builder.prepare_markup( + markup, from_encoding, exclude_encodings=exclude_encodings + ): + self.reset() + self.builder.initialize_soup(self) + try: + self._feed() + success = True + break + except ParserRejectedMarkup as e: + rejections.append(e) + pass + + if not success: + other_exceptions = [str(e) for e in rejections] + raise ParserRejectedMarkup( + "The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.\n\nOriginal exception(s) from parser:\n " + + "\n ".join(other_exceptions) + ) + + # Clear out the markup and remove the builder's circular + # reference to this object. + self.markup = None + self.builder.soup = None + + def copy_self(self) -> "BeautifulSoup": + """Create a new BeautifulSoup object with the same TreeBuilder, + but not associated with any markup. + + This is the first step of the deepcopy process. + """ + clone = type(self)("", None, self.builder) + + # Keep track of the encoding of the original document, + # since we won't be parsing it again. + clone.original_encoding = self.original_encoding + return clone + + def __getstate__(self) -> Dict[str, Any]: + # Frequently a tree builder can't be pickled. + d = dict(self.__dict__) + if "builder" in d and d["builder"] is not None and not self.builder.picklable: + d["builder"] = type(self.builder) + # Store the contents as a Unicode string. + d["contents"] = [] + d["markup"] = self.decode() + + # If _most_recent_element is present, it's a Tag object left + # over from initial parse. It might not be picklable and we + # don't need it. + if "_most_recent_element" in d: + del d["_most_recent_element"] + return d + + def __setstate__(self, state: Dict[str, Any]) -> None: + # If necessary, restore the TreeBuilder by looking it up. + self.__dict__ = state + if isinstance(self.builder, type): + self.builder = self.builder() + elif not self.builder: + # We don't know which builder was used to build this + # parse tree, so use a default we know is always available. + self.builder = HTMLParserTreeBuilder() + self.builder.soup = self + self.reset() + self._feed() + + @classmethod + @_deprecated( + replaced_by="nothing (private method, will be removed)", version="4.13.0" + ) + def _decode_markup(cls, markup: _RawMarkup) -> str: + """Ensure `markup` is Unicode so it's safe to send into warnings.warn. + + warnings.warn had this problem back in 2010 but fortunately + not anymore. This has not been used for a long time; I just + noticed that fact while working on 4.13.0. + """ + if isinstance(markup, bytes): + decoded = markup.decode("utf-8", "replace") + else: + decoded = markup + return decoded + + @classmethod + def _markup_is_url(cls, markup: _RawMarkup) -> bool: + """Error-handling method to raise a warning if incoming markup looks + like a URL. + + :param markup: A string of markup. + :return: Whether or not the markup resembled a URL + closely enough to justify issuing a warning. + """ + problem: bool = False + if isinstance(markup, bytes): + problem = ( + any(markup.startswith(prefix) for prefix in (b"http:", b"https:")) + and b" " not in markup + ) + elif isinstance(markup, str): + problem = ( + any(markup.startswith(prefix) for prefix in ("http:", "https:")) + and " " not in markup + ) + else: + return False + + if not problem: + return False + warnings.warn( + MarkupResemblesLocatorWarning.URL_MESSAGE % dict(what="URL"), + MarkupResemblesLocatorWarning, + stacklevel=3, + ) + return True + + @classmethod + def _markup_resembles_filename(cls, markup: _RawMarkup) -> bool: + """Error-handling method to issue a warning if incoming markup + resembles a filename. + + :param markup: A string of markup. + :return: Whether or not the markup resembled a filename + closely enough to justify issuing a warning. + """ + markup_b: bytes + + # We're only checking ASCII characters, so rather than write + # the same tests twice, convert Unicode to a bytestring and + # operate on the bytestring. + if isinstance(markup, str): + markup_b = markup.encode("utf8") + else: + markup_b = markup + + # Step 1: does it end with a common textual file extension? + filelike = False + lower = markup_b.lower() + extensions = [b".html", b".htm", b".xml", b".xhtml", b".txt"] + if any(lower.endswith(ext) for ext in extensions): + filelike = True + if not filelike: + return False + + # Step 2: it _might_ be a file, but there are a few things + # we can look for that aren't very common in filenames. + + # Characters that have special meaning to Unix shells. (< was + # excluded before this method was called.) + # + # Many of these are also reserved characters that cannot + # appear in Windows filenames. + for byte in markup_b: + if byte in b"?*#&;>$|": + return False + + # Two consecutive forward slashes (as seen in a URL) or two + # consecutive spaces (as seen in fixed-width data). + # + # (Paths to Windows network shares contain consecutive + # backslashes, so checking that doesn't seem as helpful.) + if b"//" in markup_b: + return False + if b" " in markup_b: + return False + + # A colon in any position other than position 1 (e.g. after a + # Windows drive letter). + if markup_b.startswith(b":"): + return False + colon_i = markup_b.rfind(b":") + if colon_i not in (-1, 1): + return False + + # Step 3: If it survived all of those checks, it's similar + # enough to a file to justify issuing a warning. + warnings.warn( + MarkupResemblesLocatorWarning.FILENAME_MESSAGE % dict(what="filename"), + MarkupResemblesLocatorWarning, + stacklevel=3, + ) + return True + + def _feed(self) -> None: + """Internal method that parses previously set markup, creating a large + number of Tag and NavigableString objects. + """ + # Convert the document to Unicode. + self.builder.reset() + + if self.markup is not None: + self.builder.feed(self.markup) + # Close out any unfinished strings and close all the open tags. + self.endData() + while ( + self.currentTag is not None and self.currentTag.name != self.ROOT_TAG_NAME + ): + self.popTag() + + def reset(self) -> None: + """Reset this object to a state as though it had never parsed any + markup. + """ + Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME) + self.hidden = True + self.builder.reset() + self.current_data = [] + self.currentTag = None + self.tagStack = [] + self.open_tag_counter = Counter() + self.preserve_whitespace_tag_stack = [] + self.string_container_stack = [] + self._most_recent_element = None + self.pushTag(self) + + def new_tag( + self, + name: str, + namespace: Optional[str] = None, + nsprefix: Optional[str] = None, + attrs: Optional[_RawAttributeValues] = None, + sourceline: Optional[int] = None, + sourcepos: Optional[int] = None, + string: Optional[str] = None, + **kwattrs: _RawAttributeValue, + ) -> Tag: + """Create a new Tag associated with this BeautifulSoup object. + + :param name: The name of the new Tag. + :param namespace: The URI of the new Tag's XML namespace, if any. + :param prefix: The prefix for the new Tag's XML namespace, if any. + :param attrs: A dictionary of this Tag's attribute values; can + be used instead of ``kwattrs`` for attributes like 'class' + that are reserved words in Python. + :param sourceline: The line number where this tag was + (purportedly) found in its source document. + :param sourcepos: The character position within ``sourceline`` where this + tag was (purportedly) found. + :param string: String content for the new Tag, if any. + :param kwattrs: Keyword arguments for the new Tag's attribute values. + + """ + attr_container = self.builder.attribute_dict_class(**kwattrs) + if attrs is not None: + attr_container.update(attrs) + tag_class = self.element_classes.get(Tag, Tag) + + # Assume that this is either Tag or a subclass of Tag. If not, + # the user brought type-unsafety upon themselves. + tag_class = cast(Type[Tag], tag_class) + tag = tag_class( + None, + self.builder, + name, + namespace, + nsprefix, + attr_container, + sourceline=sourceline, + sourcepos=sourcepos, + ) + + if string is not None: + tag.string = string + return tag + + def string_container( + self, base_class: Optional[Type[NavigableString]] = None + ) -> Type[NavigableString]: + """Find the class that should be instantiated to hold a given kind of + string. + + This may be a built-in Beautiful Soup class or a custom class passed + in to the BeautifulSoup constructor. + """ + container = base_class or NavigableString + + # The user may want us to use some other class (hopefully a + # custom subclass) instead of the one we'd use normally. + container = cast( + Type[NavigableString], self.element_classes.get(container, container) + ) + + # On top of that, we may be inside a tag that needs a special + # container class. + if self.string_container_stack and container is NavigableString: + container = self.builder.string_containers.get( + self.string_container_stack[-1].name, container + ) + return container + + def new_string( + self, s: str, subclass: Optional[Type[NavigableString]] = None + ) -> NavigableString: + """Create a new `NavigableString` associated with this `BeautifulSoup` + object. + + :param s: The string content of the `NavigableString` + :param subclass: The subclass of `NavigableString`, if any, to + use. If a document is being processed, an appropriate + subclass for the current location in the document will + be determined automatically. + """ + container = self.string_container(subclass) + return container(s) + + def insert_before(self, *args: _InsertableElement) -> List[PageElement]: + """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement + it because there is nothing before or after it in the parse tree. + """ + raise NotImplementedError( + "BeautifulSoup objects don't support insert_before()." + ) + + def insert_after(self, *args: _InsertableElement) -> List[PageElement]: + """This method is part of the PageElement API, but `BeautifulSoup` doesn't implement + it because there is nothing before or after it in the parse tree. + """ + raise NotImplementedError("BeautifulSoup objects don't support insert_after().") + + def popTag(self) -> Optional[Tag]: + """Internal method called by _popToTag when a tag is closed. + + :meta private: + """ + if not self.tagStack: + # Nothing to pop. This shouldn't happen. + return None + tag = self.tagStack.pop() + if tag.name in self.open_tag_counter: + self.open_tag_counter[tag.name] -= 1 + if ( + self.preserve_whitespace_tag_stack + and tag == self.preserve_whitespace_tag_stack[-1] + ): + self.preserve_whitespace_tag_stack.pop() + if self.string_container_stack and tag == self.string_container_stack[-1]: + self.string_container_stack.pop() + # print("Pop", tag.name) + if self.tagStack: + self.currentTag = self.tagStack[-1] + return self.currentTag + + def pushTag(self, tag: Tag) -> None: + """Internal method called by handle_starttag when a tag is opened. + + :meta private: + """ + # print("Push", tag.name) + if self.currentTag is not None: + self.currentTag.contents.append(tag) + self.tagStack.append(tag) + self.currentTag = self.tagStack[-1] + if tag.name != self.ROOT_TAG_NAME: + self.open_tag_counter[tag.name] += 1 + if tag.name in self.builder.preserve_whitespace_tags: + self.preserve_whitespace_tag_stack.append(tag) + if tag.name in self.builder.string_containers: + self.string_container_stack.append(tag) + + def endData(self, containerClass: Optional[Type[NavigableString]] = None) -> None: + """Method called by the TreeBuilder when the end of a data segment + occurs. + + :param containerClass: The class to use when incorporating the + data segment into the parse tree. + + :meta private: + """ + if self.current_data: + current_data = "".join(self.current_data) + # If whitespace is not preserved, and this string contains + # nothing but ASCII spaces, replace it with a single space + # or newline. + if not self.preserve_whitespace_tag_stack: + strippable = True + for i in current_data: + if i not in self.ASCII_SPACES: + strippable = False + break + if strippable: + if "\n" in current_data: + current_data = "\n" + else: + current_data = " " + + # Reset the data collector. + self.current_data = [] + + # Should we add this string to the tree at all? + if ( + self.parse_only + and len(self.tagStack) <= 1 + and (not self.parse_only.allow_string_creation(current_data)) + ): + return + + containerClass = self.string_container(containerClass) + o = containerClass(current_data) + self.object_was_parsed(o) + + def object_was_parsed( + self, + o: PageElement, + parent: Optional[Tag] = None, + most_recent_element: Optional[PageElement] = None, + ) -> None: + """Method called by the TreeBuilder to integrate an object into the + parse tree. + + :meta private: + """ + if parent is None: + parent = self.currentTag + assert parent is not None + previous_element: Optional[PageElement] + if most_recent_element is not None: + previous_element = most_recent_element + else: + previous_element = self._most_recent_element + + next_element = previous_sibling = next_sibling = None + if isinstance(o, Tag): + next_element = o.next_element + next_sibling = o.next_sibling + previous_sibling = o.previous_sibling + if previous_element is None: + previous_element = o.previous_element + + fix = parent.next_element is not None + + o.setup(parent, previous_element, next_element, previous_sibling, next_sibling) + + self._most_recent_element = o + parent.contents.append(o) + + # Check if we are inserting into an already parsed node. + if fix: + self._linkage_fixer(parent) + + def _linkage_fixer(self, el: Tag) -> None: + """Make sure linkage of this fragment is sound.""" + + first = el.contents[0] + child = el.contents[-1] + descendant: PageElement = child + + if child is first and el.parent is not None: + # Parent should be linked to first child + el.next_element = child + # We are no longer linked to whatever this element is + prev_el = child.previous_element + if prev_el is not None and prev_el is not el: + prev_el.next_element = None + # First child should be linked to the parent, and no previous siblings. + child.previous_element = el + child.previous_sibling = None + + # We have no sibling as we've been appended as the last. + child.next_sibling = None + + # This index is a tag, dig deeper for a "last descendant" + if isinstance(child, Tag) and child.contents: + # _last_decendant is typed as returning Optional[PageElement], + # but the value can't be None here, because el is a Tag + # which we know has contents. + descendant = cast(PageElement, child._last_descendant(False)) + + # As the final step, link last descendant. It should be linked + # to the parent's next sibling (if found), else walk up the chain + # and find a parent with a sibling. It should have no next sibling. + descendant.next_element = None + descendant.next_sibling = None + + target: Optional[Tag] = el + while True: + if target is None: + break + elif target.next_sibling is not None: + descendant.next_element = target.next_sibling + target.next_sibling.previous_element = child + break + target = target.parent + + def _popToTag( + self, name: str, nsprefix: Optional[str] = None, inclusivePop: bool = True + ) -> Optional[Tag]: + """Pops the tag stack up to and including the most recent + instance of the given tag. + + If there are no open tags with the given name, nothing will be + popped. + + :param name: Pop up to the most recent tag with this name. + :param nsprefix: The namespace prefix that goes with `name`. + :param inclusivePop: It this is false, pops the tag stack up + to but *not* including the most recent instqance of the + given tag. + + :meta private: + """ + # print("Popping to %s" % name) + if name == self.ROOT_TAG_NAME: + # The BeautifulSoup object itself can never be popped. + return None + + most_recently_popped = None + + stack_size = len(self.tagStack) + for i in range(stack_size - 1, 0, -1): + if not self.open_tag_counter.get(name): + break + t = self.tagStack[i] + if name == t.name and nsprefix == t.prefix: + if inclusivePop: + most_recently_popped = self.popTag() + break + most_recently_popped = self.popTag() + + return most_recently_popped + + def handle_starttag( + self, + name: str, + namespace: Optional[str], + nsprefix: Optional[str], + attrs: _RawAttributeValues, + sourceline: Optional[int] = None, + sourcepos: Optional[int] = None, + namespaces: Optional[Dict[str, str]] = None, + ) -> Optional[Tag]: + """Called by the tree builder when a new tag is encountered. + + :param name: Name of the tag. + :param nsprefix: Namespace prefix for the tag. + :param attrs: A dictionary of attribute values. Note that + attribute values are expected to be simple strings; processing + of multi-valued attributes such as "class" comes later. + :param sourceline: The line number where this tag was found in its + source document. + :param sourcepos: The character position within `sourceline` where this + tag was found. + :param namespaces: A dictionary of all namespace prefix mappings + currently in scope in the document. + + If this method returns None, the tag was rejected by an active + `ElementFilter`. You should proceed as if the tag had not occurred + in the document. For instance, if this was a self-closing tag, + don't call handle_endtag. + + :meta private: + """ + # print("Start tag %s: %s" % (name, attrs)) + self.endData() + + if ( + self.parse_only + and len(self.tagStack) <= 1 + and not self.parse_only.allow_tag_creation(nsprefix, name, attrs) + ): + return None + + tag_class = self.element_classes.get(Tag, Tag) + # Assume that this is either Tag or a subclass of Tag. If not, + # the user brought type-unsafety upon themselves. + tag_class = cast(Type[Tag], tag_class) + tag = tag_class( + self, + self.builder, + name, + namespace, + nsprefix, + attrs, + self.currentTag, + self._most_recent_element, + sourceline=sourceline, + sourcepos=sourcepos, + namespaces=namespaces, + ) + if tag is None: + return tag + if self._most_recent_element is not None: + self._most_recent_element.next_element = tag + self._most_recent_element = tag + self.pushTag(tag) + return tag + + def handle_endtag(self, name: str, nsprefix: Optional[str] = None) -> None: + """Called by the tree builder when an ending tag is encountered. + + :param name: Name of the tag. + :param nsprefix: Namespace prefix for the tag. + + :meta private: + """ + # print("End tag: " + name) + self.endData() + self._popToTag(name, nsprefix) + + def handle_data(self, data: str) -> None: + """Called by the tree builder when a chunk of textual data is + encountered. + + :meta private: + """ + self.current_data.append(data) + + def decode( + self, + indent_level: Optional[int] = None, + eventual_encoding: _Encoding = DEFAULT_OUTPUT_ENCODING, + formatter: Union[Formatter, str] = "minimal", + iterator: Optional[Iterator[PageElement]] = None, + **kwargs: Any, + ) -> str: + """Returns a string representation of the parse tree + as a full HTML or XML document. + + :param indent_level: Each line of the rendering will be + indented this many levels. (The ``formatter`` decides what a + 'level' means, in terms of spaces or other characters + output.) This is used internally in recursive calls while + pretty-printing. + :param eventual_encoding: The encoding of the final document. + If this is None, the document will be a Unicode string. + :param formatter: Either a `Formatter` object, or a string naming one of + the standard formatters. + :param iterator: The iterator to use when navigating over the + parse tree. This is only used by `Tag.decode_contents` and + you probably won't need to use it. + """ + if self.is_xml: + # Print the XML declaration + encoding_part = "" + declared_encoding: Optional[str] = eventual_encoding + if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS: + # This is a special Python encoding; it can't actually + # go into an XML document because it means nothing + # outside of Python. + declared_encoding = None + if declared_encoding is not None: + encoding_part = ' encoding="%s"' % declared_encoding + prefix = '\n' % encoding_part + else: + prefix = "" + + # Prior to 4.13.0, the first argument to this method was a + # bool called pretty_print, which gave the method a different + # signature from its superclass implementation, Tag.decode. + # + # The signatures of the two methods now match, but just in + # case someone is still passing a boolean in as the first + # argument to this method (or a keyword argument with the old + # name), we can handle it and put out a DeprecationWarning. + warning: Optional[str] = None + pretty_print: Optional[bool] = None + if isinstance(indent_level, bool): + if indent_level is True: + indent_level = 0 + elif indent_level is False: + indent_level = None + warning = f"As of 4.13.0, the first argument to BeautifulSoup.decode has been changed from bool to int, to match Tag.decode. Pass in a value of {indent_level} instead." + else: + pretty_print = kwargs.pop("pretty_print", None) + assert not kwargs + if pretty_print is not None: + if pretty_print is True: + indent_level = 0 + elif pretty_print is False: + indent_level = None + warning = f"As of 4.13.0, the pretty_print argument to BeautifulSoup.decode has been removed, to match Tag.decode. Pass in a value of indent_level={indent_level} instead." + + if warning: + warnings.warn(warning, DeprecationWarning, stacklevel=2) + elif indent_level is False or pretty_print is False: + indent_level = None + return prefix + super(BeautifulSoup, self).decode( + indent_level, eventual_encoding, formatter, iterator + ) + + +# Aliases to make it easier to get started quickly, e.g. 'from bs4 import _soup' +_s = BeautifulSoup +_soup = BeautifulSoup + + +class BeautifulStoneSoup(BeautifulSoup): + """Deprecated interface to an XML parser.""" + + def __init__(self, *args: Any, **kwargs: Any): + kwargs["features"] = "xml" + warnings.warn( + "The BeautifulStoneSoup class was deprecated in version 4.0.0. Instead of using " + 'it, pass features="xml" into the BeautifulSoup constructor.', + DeprecationWarning, + stacklevel=2, + ) + super(BeautifulStoneSoup, self).__init__(*args, **kwargs) + + +# If this file is run as a script, act as an HTML pretty-printer. +if __name__ == "__main__": + import sys + + soup = BeautifulSoup(sys.stdin) + print((soup.prettify())) diff --git a/python/py313/Lib/site-packages/bs4/_deprecation.py b/python/py313/Lib/site-packages/bs4/_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7b5685b8ab8b40597e1f006e721ae2cc12c4b03 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/_deprecation.py @@ -0,0 +1,80 @@ +"""Helper functions for deprecation. + +This interface is itself unstable and may change without warning. Do +not use these functions yourself, even as a joke. The underscores are +there for a reason. No support will be given. + +In particular, most of this will go away without warning once +Beautiful Soup drops support for Python 3.11, since Python 3.12 +defines a `@typing.deprecated() +decorator. `_ +""" + +import functools +import warnings + +from typing import ( + Any, + Callable, +) + + +def _deprecated_alias(old_name: str, new_name: str, version: str): + """Alias one attribute name to another for backward compatibility + + :meta private: + """ + + @property # type:ignore + def alias(self) -> Any: + ":meta private:" + warnings.warn( + f"Access to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(self, new_name) + + @alias.setter + def alias(self, value: str) -> None: + ":meta private:" + warnings.warn( + f"Write to deprecated property {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return setattr(self, new_name, value) + + return alias + + +def _deprecated_function_alias( + old_name: str, new_name: str, version: str +) -> Callable[[Any], Any]: + def alias(self, *args: Any, **kwargs: Any) -> Any: + ":meta private:" + warnings.warn( + f"Call to deprecated method {old_name}. (Replaced by {new_name}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(self, new_name)(*args, **kwargs) + + return alias + + +def _deprecated(replaced_by: str, version: str) -> Callable: + def deprecate(func: Callable) -> Callable: + @functools.wraps(func) + def with_warning(*args: Any, **kwargs: Any) -> Any: + ":meta private:" + warnings.warn( + f"Call to deprecated method {func.__name__}. (Replaced by {replaced_by}) -- Deprecated since version {version}.", + DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return with_warning + + return deprecate diff --git a/python/py313/Lib/site-packages/bs4/_typing.py b/python/py313/Lib/site-packages/bs4/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab69df14360e9b344a1e165bab77eebffdb8eb6 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/_typing.py @@ -0,0 +1,205 @@ +# Custom type aliases used throughout Beautiful Soup to improve readability. + +# Notes on improvements to the type system in newer versions of Python +# that can be used once Beautiful Soup drops support for older +# versions: +# +# * ClassVar can be put on class variables now. +# * In 3.10, x|y is an accepted shorthand for Union[x,y]. +# * In 3.10, TypeAlias gains capabilities that can be used to +# improve the tree matching types (I don't remember what, exactly). +# * In 3.9 it's possible to specialize the re.Match type, +# e.g. re.Match[str]. In 3.8 there's a typing.re namespace for this, +# but it's removed in 3.12, so to support the widest possible set of +# versions I'm not using it. + +from typing_extensions import ( + runtime_checkable, + Protocol, + TypeAlias, +) +from typing import ( + Any, + Callable, + Dict, + IO, + Iterable, + Mapping, + Optional, + Pattern, + TYPE_CHECKING, + Union, +) + +if TYPE_CHECKING: + from bs4.element import ( + AttributeValueList, + NamespacedAttribute, + NavigableString, + PageElement, + ResultSet, + Tag, + ) + + +@runtime_checkable +class _RegularExpressionProtocol(Protocol): + """A protocol object which can accept either Python's built-in + `re.Pattern` objects, or the similar ``Regex`` objects defined by the + third-party ``regex`` package. + """ + + def search( + self, string: str, pos: int = ..., endpos: int = ... + ) -> Optional[Any]: ... + + @property + def pattern(self) -> str: ... + + +# Aliases for markup in various stages of processing. +# +#: The rawest form of markup: either a string, bytestring, or an open filehandle. +_IncomingMarkup: TypeAlias = Union[str, bytes, IO[str], IO[bytes]] + +#: Markup that is in memory but has (potentially) yet to be converted +#: to Unicode. +_RawMarkup: TypeAlias = Union[str, bytes] + +# Aliases for character encodings +# + +#: A data encoding. +_Encoding: TypeAlias = str + +#: One or more data encodings. +_Encodings: TypeAlias = Iterable[_Encoding] + +# Aliases for XML namespaces +# + +#: The prefix for an XML namespace. +_NamespacePrefix: TypeAlias = str + +#: The URL of an XML namespace +_NamespaceURL: TypeAlias = str + +#: A mapping of prefixes to namespace URLs. +_NamespaceMapping: TypeAlias = Dict[_NamespacePrefix, _NamespaceURL] + +#: A mapping of namespace URLs to prefixes +_InvertedNamespaceMapping: TypeAlias = Dict[_NamespaceURL, _NamespacePrefix] + +# Aliases for the attribute values associated with HTML/XML tags. +# + +#: The value associated with an HTML or XML attribute. This is the +#: relatively unprocessed value Beautiful Soup expects to come from a +#: `TreeBuilder`. +_RawAttributeValue: TypeAlias = str + +#: A dictionary of names to `_RawAttributeValue` objects. This is how +#: Beautiful Soup expects a `TreeBuilder` to represent a tag's +#: attribute values. +_RawAttributeValues: TypeAlias = ( + "Mapping[Union[str, NamespacedAttribute], _RawAttributeValue]" +) + +#: An attribute value in its final form, as stored in the +# `Tag` class, after it has been processed and (in some cases) +# split into a list of strings. +_AttributeValue: TypeAlias = Union[str, "AttributeValueList"] + +#: A dictionary of names to :py:data:`_AttributeValue` objects. This is what +#: a tag's attributes look like after processing. +_AttributeValues: TypeAlias = Dict[str, _AttributeValue] + +#: The methods that deal with turning :py:data:`_RawAttributeValue` into +#: :py:data:`_AttributeValue` may be called several times, even after the values +#: are already processed (e.g. when cloning a tag), so they need to +#: be able to acommodate both possibilities. +_RawOrProcessedAttributeValues: TypeAlias = Union[_RawAttributeValues, _AttributeValues] + +#: A number of tree manipulation methods can take either a `PageElement` or a +#: normal Python string (which will be converted to a `NavigableString`). +_InsertableElement: TypeAlias = Union["PageElement", str] + +# Aliases to represent the many possibilities for matching bits of a +# parse tree. +# +# This is very complicated because we're applying a formal type system +# to some very DWIM code. The types we end up with will be the types +# of the arguments to the SoupStrainer constructor and (more +# familiarly to Beautiful Soup users) the find* methods. + +#: A function that takes a PageElement and returns a yes-or-no answer. +_PageElementMatchFunction: TypeAlias = Callable[["PageElement"], bool] + +#: A function that takes the raw parsed ingredients of a markup tag +#: and returns a yes-or-no answer. +# Not necessary at the moment. +# _AllowTagCreationFunction:TypeAlias = Callable[[Optional[str], str, Optional[_RawAttributeValues]], bool] + +#: A function that takes the raw parsed ingredients of a markup string node +#: and returns a yes-or-no answer. +# Not necessary at the moment. +# _AllowStringCreationFunction:TypeAlias = Callable[[Optional[str]], bool] + +#: A function that takes a `Tag` and returns a yes-or-no answer. +#: A `TagNameMatchRule` expects this kind of function, if you're +#: going to pass it a function. +_TagMatchFunction: TypeAlias = Callable[["Tag"], bool] + +#: A function that takes a string (or None) and returns a yes-or-no +#: answer. An `AttributeValueMatchRule` expects this kind of function, if +#: you're going to pass it a function. +_NullableStringMatchFunction: TypeAlias = Callable[[Optional[str]], bool] + +#: A function that takes a string and returns a yes-or-no answer. A +# `StringMatchRule` expects this kind of function, if you're going to +# pass it a function. +_StringMatchFunction: TypeAlias = Callable[[str], bool] + +#: Either a tag name, an attribute value or a string can be matched +#: against a string, bytestring, regular expression, or a boolean. +_BaseStrainable: TypeAlias = Union[str, bytes, Pattern[str], bool] + +#: A tag can be matched either with the `_BaseStrainable` options, or +#: using a function that takes the `Tag` as its sole argument. +_BaseStrainableElement: TypeAlias = Union[_BaseStrainable, _TagMatchFunction] + +#: A tag's attribute value can be matched either with the +#: `_BaseStrainable` options, or using a function that takes that +#: value as its sole argument. +_BaseStrainableAttribute: TypeAlias = Union[_BaseStrainable, _NullableStringMatchFunction] + +#: A tag can be matched using either a single criterion or a list of +#: criteria. +_StrainableElement: TypeAlias = Union[ + _BaseStrainableElement, Iterable[_BaseStrainableElement] +] + +#: An attribute value can be matched using either a single criterion +#: or a list of criteria. +_StrainableAttribute: TypeAlias = Union[ + _BaseStrainableAttribute, Iterable[_BaseStrainableAttribute] +] + +#: An string can be matched using the same techniques as +#: an attribute value. +_StrainableString: TypeAlias = _StrainableAttribute + +#: A dictionary may be used to match against multiple attribute vlaues at once. +_StrainableAttributes: TypeAlias = Dict[str, _StrainableAttribute] + +#: Many Beautiful soup methods return a PageElement or an ResultSet of +#: PageElements. A PageElement is either a Tag or a NavigableString. +#: These convenience aliases make it easier for IDE users to see which methods +#: are available on the objects they're dealing with. +_OneElement: TypeAlias = Union["PageElement", "Tag", "NavigableString"] +_AtMostOneElement: TypeAlias = Optional[_OneElement] +_AtMostOneTag: TypeAlias = Optional["Tag"] +_AtMostOneNavigableString: TypeAlias = Optional["NavigableString"] +_QueryResults: TypeAlias = "ResultSet[_OneElement]" +_SomeTags: TypeAlias = "ResultSet[Tag]" +_SomeNavigableStrings: TypeAlias = "ResultSet[NavigableString]" diff --git a/python/py313/Lib/site-packages/bs4/_warnings.py b/python/py313/Lib/site-packages/bs4/_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..43094730458541fd387595dfd61c483f477b95f0 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/_warnings.py @@ -0,0 +1,98 @@ +"""Define some custom warnings.""" + + +class GuessedAtParserWarning(UserWarning): + """The warning issued when BeautifulSoup has to guess what parser to + use -- probably because no parser was specified in the constructor. + """ + + MESSAGE: str = """No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system ("%(parser)s"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. + +The code that caused this warning is on line %(line_number)s of the file %(filename)s. To get rid of this warning, pass the additional argument 'features="%(parser)s"' to the BeautifulSoup constructor. +""" + + +class UnusualUsageWarning(UserWarning): + """A superclass for warnings issued when Beautiful Soup sees + something that is typically the result of a mistake in the calling + code, but might be intentional on the part of the user. If it is + in fact intentional, you can filter the individual warning class + to get rid of the warning. If you don't like Beautiful Soup + second-guessing what you are doing, you can filter the + UnusualUsageWarningclass itself and get rid of these entirely. + """ + + +class MarkupResemblesLocatorWarning(UnusualUsageWarning): + """The warning issued when BeautifulSoup is given 'markup' that + actually looks like a resource locator -- a URL or a path to a file + on disk. + """ + + #: :meta private: + GENERIC_MESSAGE: str = """ + +However, if you want to parse some data that happens to look like a %(what)s, then nothing has gone wrong: you are using Beautiful Soup correctly, and this warning is spurious and can be filtered. To make this warning go away, run this code before calling the BeautifulSoup constructor: + + from bs4 import MarkupResemblesLocatorWarning + import warnings + + warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning) + """ + + URL_MESSAGE: str = ( + """The input passed in on this line looks more like a URL than HTML or XML. + +If you meant to use Beautiful Soup to parse the web page found at a certain URL, then something has gone wrong. You should use an Python package like 'requests' to fetch the content behind the URL. Once you have the content as a string, you can feed that string into Beautiful Soup.""" + + GENERIC_MESSAGE + ) + + FILENAME_MESSAGE: str = ( + """The input passed in on this line looks more like a filename than HTML or XML. + +If you meant to use Beautiful Soup to parse the contents of a file on disk, then something has gone wrong. You should open the file first, using code like this: + + filehandle = open(your filename) + +You can then feed the open filehandle into Beautiful Soup instead of using the filename.""" + + GENERIC_MESSAGE + ) + + +class AttributeResemblesVariableWarning(UnusualUsageWarning, SyntaxWarning): + """The warning issued when Beautiful Soup suspects a provided + attribute name may actually be the misspelled name of a Beautiful + Soup variable. Generally speaking, this is only used in cases like + "_class" where it's very unlikely the user would be referencing an + XML attribute with that name. + """ + + MESSAGE: str = """%(original)r is an unusual attribute name and is a common misspelling for %(autocorrect)r. + +If you meant %(autocorrect)r, change your code to use it, and this warning will go away. + +If you really did mean to check the %(original)r attribute, this warning is spurious and can be filtered. To make it go away, run this code before creating your BeautifulSoup object: + + from bs4 import AttributeResemblesVariableWarning + import warnings + + warnings.filterwarnings("ignore", category=AttributeResemblesVariableWarning) +""" + + +class XMLParsedAsHTMLWarning(UnusualUsageWarning): + """The warning issued when an HTML parser is used to parse + XML that is not (as far as we can tell) XHTML. + """ + + MESSAGE: str = """It looks like you're using an HTML parser to parse an XML document. + +Assuming this really is an XML document, what you're doing might work, but you should know that using an XML parser will be more reliable. To parse this document as XML, make sure you have the Python package 'lxml' installed, and pass the keyword argument `features="xml"` into the BeautifulSoup constructor. + +If you want or need to use an HTML parser on this document, you can make this warning go away by filtering it. To do that, run this code before calling the BeautifulSoup constructor: + + from bs4 import XMLParsedAsHTMLWarning + import warnings + + warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning) +""" diff --git a/python/py313/Lib/site-packages/bs4/css.py b/python/py313/Lib/site-packages/bs4/css.py new file mode 100644 index 0000000000000000000000000000000000000000..75ad998349af45e66a5fc2bbe1966960b7eab3ba --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/css.py @@ -0,0 +1,339 @@ +"""Integration code for CSS selectors using `Soup Sieve `_ (pypi: ``soupsieve``). + +Acquire a `CSS` object through the `element.Tag.css` attribute of +the starting point of your CSS selector, or (if you want to run a +selector against the entire document) of the `BeautifulSoup` object +itself. + +The main advantage of doing this instead of using ``soupsieve`` +functions is that you don't need to keep passing the `element.Tag` to be +selected against, since the `CSS` object is permanently scoped to that +`element.Tag`. + +""" + +from __future__ import annotations + +from types import ModuleType +from typing import ( + Any, + cast, + Iterable, + Iterator, + MutableSequence, + Optional, + TYPE_CHECKING, +) +import warnings +from bs4._typing import _NamespaceMapping + +if TYPE_CHECKING: + from soupsieve import SoupSieve + from bs4 import element + from bs4.element import ResultSet, Tag + +soupsieve: Optional[ModuleType] +try: + import soupsieve +except ImportError: + soupsieve = None + warnings.warn( + "The soupsieve package is not installed. CSS selectors cannot be used." + ) + + +class CSS(object): + """A proxy object against the ``soupsieve`` library, to simplify its + CSS selector API. + + You don't need to instantiate this class yourself; instead, use + `element.Tag.css`. + + :param tag: All CSS selectors run by this object will use this as + their starting point. + + :param api: An optional drop-in replacement for the ``soupsieve`` module, + intended for use in unit tests. + """ + + def __init__(self, tag: element.Tag, api: Optional[ModuleType] = None): + if api is None: + api = soupsieve + if api is None: + raise NotImplementedError( + "Cannot execute CSS selectors because the soupsieve package is not installed." + ) + self.api = api + self.tag = tag + + def escape(self, ident: str) -> str: + """Escape a CSS identifier. + + This is a simple wrapper around `soupsieve.escape() `_. See the + documentation for that function for more information. + """ + if soupsieve is None: + raise NotImplementedError( + "Cannot escape CSS identifiers because the soupsieve package is not installed." + ) + return cast(str, self.api.escape(ident)) + + def _ns( + self, ns: Optional[_NamespaceMapping], select: str + ) -> Optional[_NamespaceMapping]: + """Normalize a dictionary of namespaces.""" + if not isinstance(select, self.api.SoupSieve) and ns is None: + # If the selector is a precompiled pattern, it already has + # a namespace context compiled in, which cannot be + # replaced. + ns = self.tag._namespaces + return ns + + def _rs(self, results: MutableSequence[Tag]) -> ResultSet[Tag]: + """Normalize a list of results to a py:class:`ResultSet`. + + A py:class:`ResultSet` is more consistent with the rest of + Beautiful Soup's API, and :py:meth:`ResultSet.__getattr__` has + a helpful error message if you try to treat a list of results + as a single result (a common mistake). + """ + # Import here to avoid circular import + from bs4 import ResultSet + + return ResultSet(None, results) + + def compile( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + flags: int = 0, + **kwargs: Any, + ) -> SoupSieve: + """Pre-compile a selector and return the compiled object. + + :param selector: A CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will use the prefixes it encountered while + parsing the document. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.compile() `_ method. + + :param kwargs: Keyword arguments to be passed into Soup Sieve's + `soupsieve.compile() `_ method. + + :return: A precompiled selector object. + :rtype: soupsieve.SoupSieve + """ + return self.api.compile(select, self._ns(namespaces, select), flags, **kwargs) + + def select_one( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + flags: int = 0, + **kwargs: Any, + ) -> element.Tag | None: + """Perform a CSS selection operation on the current Tag and return the + first result, if any. + + This uses the Soup Sieve library. For more information, see + that library's documentation for the `soupsieve.select_one() `_ method. + + :param selector: A CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will use the prefixes it encountered while + parsing the document. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.select_one() `_ method. + + :param kwargs: Keyword arguments to be passed into Soup Sieve's + `soupsieve.select_one() `_ method. + """ + return self.api.select_one( + select, self.tag, self._ns(namespaces, select), flags, **kwargs + ) + + def select( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + limit: int = 0, + flags: int = 0, + **kwargs: Any, + ) -> ResultSet[element.Tag]: + """Perform a CSS selection operation on the current `element.Tag`. + + This uses the Soup Sieve library. For more information, see + that library's documentation for the `soupsieve.select() `_ method. + + :param selector: A CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will pass in the prefixes it encountered while + parsing the document. + + :param limit: After finding this number of results, stop looking. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.select() `_ method. + + :param kwargs: Keyword arguments to be passed into Soup Sieve's + `soupsieve.select() `_ method. + """ + if limit is None: + limit = 0 + + return self._rs( + self.api.select( + select, self.tag, self._ns(namespaces, select), limit, flags, **kwargs + ) + ) + + def iselect( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + limit: int = 0, + flags: int = 0, + **kwargs: Any, + ) -> Iterator[element.Tag]: + """Perform a CSS selection operation on the current `element.Tag`. + + This uses the Soup Sieve library. For more information, see + that library's documentation for the `soupsieve.iselect() + `_ + method. It is the same as select(), but it returns a generator + instead of a list. + + :param selector: A string containing a CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will pass in the prefixes it encountered while + parsing the document. + + :param limit: After finding this number of results, stop looking. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.iselect() `_ method. + + :param kwargs: Keyword arguments to be passed into Soup Sieve's + `soupsieve.iselect() `_ method. + """ + return self.api.iselect( + select, self.tag, self._ns(namespaces, select), limit, flags, **kwargs + ) + + def closest( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + flags: int = 0, + **kwargs: Any, + ) -> Optional[element.Tag]: + """Find the `element.Tag` closest to this one that matches the given selector. + + This uses the Soup Sieve library. For more information, see + that library's documentation for the `soupsieve.closest() + `_ + method. + + :param selector: A string containing a CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will pass in the prefixes it encountered while + parsing the document. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.closest() `_ method. + + :param kwargs: Keyword arguments to be passed into Soup Sieve's + `soupsieve.closest() `_ method. + + """ + return self.api.closest( + select, self.tag, self._ns(namespaces, select), flags, **kwargs + ) + + def match( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + flags: int = 0, + **kwargs: Any, + ) -> bool: + """Check whether or not this `element.Tag` matches the given CSS selector. + + This uses the Soup Sieve library. For more information, see + that library's documentation for the `soupsieve.match() + `_ + method. + + :param: a CSS selector. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will pass in the prefixes it encountered while + parsing the document. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.match() + `_ + method. + + :param kwargs: Keyword arguments to be passed into SoupSieve's + `soupsieve.match() + `_ + method. + """ + return cast( + bool, + self.api.match( + select, self.tag, self._ns(namespaces, select), flags, **kwargs + ), + ) + + def filter( + self, + select: str, + namespaces: Optional[_NamespaceMapping] = None, + flags: int = 0, + **kwargs: Any, + ) -> ResultSet[element.Tag]: + """Filter this `element.Tag`'s direct children based on the given CSS selector. + + This uses the Soup Sieve library. It works the same way as + passing a `element.Tag` into that library's `soupsieve.filter() + `_ + method. For more information, see the documentation for + `soupsieve.filter() + `_. + + :param namespaces: A dictionary mapping namespace prefixes + used in the CSS selector to namespace URIs. By default, + Beautiful Soup will pass in the prefixes it encountered while + parsing the document. + + :param flags: Flags to be passed into Soup Sieve's + `soupsieve.filter() + `_ + method. + + :param kwargs: Keyword arguments to be passed into SoupSieve's + `soupsieve.filter() + `_ + method. + """ + return self._rs( + self.api.filter( + select, self.tag, self._ns(namespaces, select), flags, **kwargs + ) + ) diff --git a/python/py313/Lib/site-packages/bs4/dammit.py b/python/py313/Lib/site-packages/bs4/dammit.py new file mode 100644 index 0000000000000000000000000000000000000000..52f0babd3fd07990fb4febd1041898a9f0ac1fc7 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/dammit.py @@ -0,0 +1,1516 @@ +# -*- coding: utf-8 -*- +"""Beautiful Soup bonus library: Unicode, Dammit + +This library converts a bytestream to Unicode through any means +necessary. It is heavily based on code from Mark Pilgrim's `Universal +Feed Parser `_, now maintained +by Kurt McKee. It does not rewrite the body of an XML or HTML document +to reflect a new encoding; that's the job of `TreeBuilder`. + +""" + +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +from html.entities import codepoint2name +from collections import defaultdict +import codecs +from html.entities import html5 +import re +from logging import Logger, getLogger +from types import ModuleType +from typing import ( + Dict, + Iterator, + List, + Optional, + Pattern, + Set, + Tuple, + Type, + Union, + cast, +) +from typing_extensions import Literal +from bs4._typing import ( + _Encoding, + _Encodings, +) +import warnings + +# Import a library to autodetect character encodings. We'll support +# any of a number of libraries that all support the same API: +# +# * cchardet +# * chardet +# * charset-normalizer +chardet_module: Optional[ModuleType] = None +try: + # PyPI package: cchardet + import cchardet # type:ignore + + chardet_module = cchardet +except ImportError: + try: + # Debian package: python-chardet + # PyPI package: chardet + import chardet + + chardet_module = chardet + except ImportError: + try: + # PyPI package: charset-normalizer + import charset_normalizer # type:ignore + + chardet_module = charset_normalizer + except ImportError: + # No chardet available. + pass + + +def _chardet_dammit(s: bytes) -> Optional[str]: + """Try as hard as possible to detect the encoding of a bytestring.""" + if chardet_module is None or isinstance(s, str): + return None + module = chardet_module + return module.detect(s)["encoding"] + + +# Build bytestring and Unicode versions of regular expressions for finding +# a declared encoding inside an XML or HTML document. +xml_encoding: str = "^\\s*<\\?.*encoding=['\"](.*?)['\"].*\\?>" #: :meta private: +html_meta: str = ( + "<\\s*meta[^>]+charset\\s*=\\s*[\"']?([^>]*?)[ /;'\">]" #: :meta private: +) + +# TODO-TYPING: The Pattern type here could use more refinement, but it's tricky. +encoding_res: Dict[Type, Dict[str, Pattern]] = dict() +encoding_res[bytes] = { + "html": re.compile(html_meta.encode("ascii"), re.I), + "xml": re.compile(xml_encoding.encode("ascii"), re.I), +} +encoding_res[str] = { + "html": re.compile(html_meta, re.I), + "xml": re.compile(xml_encoding, re.I), +} + + +class EntitySubstitution(object): + """The ability to substitute XML or HTML entities for certain characters.""" + + #: A map of named HTML entities to the corresponding Unicode string. + #: + #: :meta hide-value: + HTML_ENTITY_TO_CHARACTER: Dict[str, str] + + #: A map of Unicode strings to the corresponding named HTML entities; + #: the inverse of HTML_ENTITY_TO_CHARACTER. + #: + #: :meta hide-value: + CHARACTER_TO_HTML_ENTITY: Dict[str, str] + + #: A regular expression that matches any character (or, in rare + #: cases, pair of characters) that can be replaced with a named + #: HTML entity. + #: + #: :meta hide-value: + CHARACTER_TO_HTML_ENTITY_RE: Pattern[str] + + #: A very similar regular expression to + #: CHARACTER_TO_HTML_ENTITY_RE, but which also matches unescaped + #: ampersands. This is used by the 'html' formatted to provide + #: backwards-compatibility, even though the HTML5 spec allows most + #: ampersands to go unescaped. + #: + #: :meta hide-value: + CHARACTER_TO_HTML_ENTITY_WITH_AMPERSAND_RE: Pattern[str] + + @classmethod + def _populate_class_variables(cls) -> None: + """Initialize variables used by this class to manage the plethora of + HTML5 named entities. + + This function sets the following class variables: + + CHARACTER_TO_HTML_ENTITY - A mapping of Unicode strings like "⦨" to + entity names like "angmsdaa". When a single Unicode string has + multiple entity names, we try to choose the most commonly-used + name. + + HTML_ENTITY_TO_CHARACTER: A mapping of entity names like "angmsdaa" to + Unicode strings like "⦨". + + CHARACTER_TO_HTML_ENTITY_RE: A regular expression matching (almost) any + Unicode string that corresponds to an HTML5 named entity. + + CHARACTER_TO_HTML_ENTITY_WITH_AMPERSAND_RE: A very similar + regular expression to CHARACTER_TO_HTML_ENTITY_RE, but which + also matches unescaped ampersands. This is used by the 'html' + formatted to provide backwards-compatibility, even though the HTML5 + spec allows most ampersands to go unescaped. + """ + unicode_to_name = {} + name_to_unicode = {} + + short_entities = set() + long_entities_by_first_character = defaultdict(set) + + for name_with_semicolon, character in sorted(html5.items()): + # "It is intentional, for legacy compatibility, that many + # code points have multiple character reference names. For + # example, some appear both with and without the trailing + # semicolon, or with different capitalizations." + # - https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references + # + # The parsers are in charge of handling (or not) character + # references with no trailing semicolon, so we remove the + # semicolon whenever it appears. + if name_with_semicolon.endswith(";"): + name = name_with_semicolon[:-1] + else: + name = name_with_semicolon + + # When parsing HTML, we want to recognize any known named + # entity and convert it to a sequence of Unicode + # characters. + if name not in name_to_unicode: + name_to_unicode[name] = character + + # When _generating_ HTML, we want to recognize special + # character sequences that _could_ be converted to named + # entities. + unicode_to_name[character] = name + + # We also need to build a regular expression that lets us + # _find_ those characters in output strings so we can + # replace them. + # + # This is tricky, for two reasons. + + if len(character) == 1 and ord(character) < 128 and character not in "<>": + # First, it would be annoying to turn single ASCII + # characters like | into named entities like + # |. The exceptions are <>, which we _must_ + # turn into named entities to produce valid HTML. + continue + + if len(character) > 1 and all(ord(x) < 128 for x in character): + # We also do not want to turn _combinations_ of ASCII + # characters like 'fj' into named entities like 'fj', + # though that's more debateable. + continue + + # Second, some named entities have a Unicode value that's + # a subset of the Unicode value for some _other_ named + # entity. As an example, \u2267' is ≧, + # but '\u2267\u0338' is ≧̸. Our regular + # expression needs to match the first two characters of + # "\u2267\u0338foo", but only the first character of + # "\u2267foo". + # + # In this step, we build two sets of characters that + # _eventually_ need to go into the regular expression. But + # we won't know exactly what the regular expression needs + # to look like until we've gone through the entire list of + # named entities. + if len(character) == 1 and character != "&": + short_entities.add(character) + else: + long_entities_by_first_character[character[0]].add(character) + + # Now that we've been through the entire list of entities, we + # can create a regular expression that matches any of them. + particles = set() + for short in short_entities: + long_versions = long_entities_by_first_character[short] + if not long_versions: + particles.add(short) + else: + ignore = "".join([x[1] for x in long_versions]) + # This finds, e.g. \u2267 but only if it is _not_ + # followed by \u0338. + particles.add("%s(?![%s])" % (short, ignore)) + + for long_entities in list(long_entities_by_first_character.values()): + for long_entity in long_entities: + particles.add(long_entity) + + re_definition = "(%s)" % "|".join(particles) + + particles.add("&") + re_definition_with_ampersand = "(%s)" % "|".join(particles) + + # If an entity shows up in both html5 and codepoint2name, it's + # likely that HTML5 gives it several different names, such as + # 'rsquo' and 'rsquor'. When converting Unicode characters to + # named entities, the codepoint2name name should take + # precedence where possible, since that's the more easily + # recognizable one. + for codepoint, name in list(codepoint2name.items()): + character = chr(codepoint) + unicode_to_name[character] = name + + cls.CHARACTER_TO_HTML_ENTITY = unicode_to_name + cls.HTML_ENTITY_TO_CHARACTER = name_to_unicode + cls.CHARACTER_TO_HTML_ENTITY_RE = re.compile(re_definition) + cls.CHARACTER_TO_HTML_ENTITY_WITH_AMPERSAND_RE = re.compile( + re_definition_with_ampersand + ) + + #: A map of Unicode strings to the corresponding named XML entities. + #: + #: :meta hide-value: + CHARACTER_TO_XML_ENTITY: Dict[str, str] = { + "'": "apos", + '"': "quot", + "&": "amp", + "<": "lt", + ">": "gt", + } + + # Matches any named or numeric HTML entity. + ANY_ENTITY_RE = re.compile("&(#\\d+|#x[0-9a-fA-F]+|\\w+);", re.I) + + #: A regular expression matching an angle bracket or an ampersand that + #: is not part of an XML or HTML entity. + #: + #: :meta hide-value: + BARE_AMPERSAND_OR_BRACKET: Pattern[str] = re.compile( + "([<>]|" "&(?!#\\d+;|#x[0-9a-fA-F]+;|\\w+;)" ")" + ) + + #: A regular expression matching an angle bracket or an ampersand. + #: + #: :meta hide-value: + AMPERSAND_OR_BRACKET: Pattern[str] = re.compile("([<>&])") + + @classmethod + def _substitute_html_entity(cls, matchobj: re.Match) -> str: + """Used with a regular expression to substitute the + appropriate HTML entity for a special character string.""" + original_entity = matchobj.group(0) + entity = cls.CHARACTER_TO_HTML_ENTITY.get(original_entity) + if entity is None: + return "&%s;" % original_entity + return "&%s;" % entity + + @classmethod + def _substitute_xml_entity(cls, matchobj: re.Match) -> str: + """Used with a regular expression to substitute the + appropriate XML entity for a special character string.""" + entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)] + return "&%s;" % entity + + @classmethod + def _escape_entity_name(cls, matchobj: re.Match) -> str: + return "&%s;" % matchobj.group(1) + + @classmethod + def _escape_unrecognized_entity_name(cls, matchobj: re.Match) -> str: + possible_entity = matchobj.group(1) + if possible_entity in cls.HTML_ENTITY_TO_CHARACTER: + return "&%s;" % possible_entity + return "&%s;" % possible_entity + + @classmethod + def quoted_attribute_value(cls, value: str) -> str: + """Make a value into a quoted XML attribute, possibly escaping it. + + Most strings will be quoted using double quotes. + + Bob's Bar -> "Bob's Bar" + + If a string contains double quotes, it will be quoted using + single quotes. + + Welcome to "my bar" -> 'Welcome to "my bar"' + + If a string contains both single and double quotes, the + double quotes will be escaped, and the string will be quoted + using double quotes. + + Welcome to "Bob's Bar" -> Welcome to "Bob's bar" + + :param value: The XML attribute value to quote + :return: The quoted value + """ + quote_with = '"' + if '"' in value: + if "'" in value: + # The string contains both single and double + # quotes. Turn the double quotes into + # entities. We quote the double quotes rather than + # the single quotes because the entity name is + # """ whether this is HTML or XML. If we + # quoted the single quotes, we'd have to decide + # between ' and &squot;. + replace_with = """ + value = value.replace('"', replace_with) + else: + # There are double quotes but no single quotes. + # We can use single quotes to quote the attribute. + quote_with = "'" + return quote_with + value + quote_with + + @classmethod + def substitute_xml(cls, value: str, make_quoted_attribute: bool = False) -> str: + """Replace special XML characters with named XML entities. + + The less-than sign will become <, the greater-than sign + will become >, and any ampersands will become &. If you + want ampersands that seem to be part of an entity definition + to be left alone, use `substitute_xml_containing_entities` + instead. + + :param value: A string to be substituted. + + :param make_quoted_attribute: If True, then the string will be + quoted, as befits an attribute value. + + :return: A version of ``value`` with special characters replaced + with named entities. + """ + # Escape angle brackets and ampersands. + value = cls.AMPERSAND_OR_BRACKET.sub(cls._substitute_xml_entity, value) + + if make_quoted_attribute: + value = cls.quoted_attribute_value(value) + return value + + @classmethod + def substitute_xml_containing_entities( + cls, value: str, make_quoted_attribute: bool = False + ) -> str: + """Substitute XML entities for special XML characters. + + :param value: A string to be substituted. The less-than sign will + become <, the greater-than sign will become >, and any + ampersands that are not part of an entity defition will + become &. + + :param make_quoted_attribute: If True, then the string will be + quoted, as befits an attribute value. + """ + # Escape angle brackets, and ampersands that aren't part of + # entities. + value = cls.BARE_AMPERSAND_OR_BRACKET.sub(cls._substitute_xml_entity, value) + + if make_quoted_attribute: + value = cls.quoted_attribute_value(value) + return value + + @classmethod + def substitute_html(cls, s: str) -> str: + """Replace certain Unicode characters with named HTML entities. + + This differs from ``data.encode(encoding, 'xmlcharrefreplace')`` + in that the goal is to make the result more readable (to those + with ASCII displays) rather than to recover from + errors. There's absolutely nothing wrong with a UTF-8 string + containg a LATIN SMALL LETTER E WITH ACUTE, but replacing that + character with "é" will make it more readable to some + people. + + :param s: The string to be modified. + :return: The string with some Unicode characters replaced with + HTML entities. + """ + # Convert any appropriate characters to HTML entities. + return cls.CHARACTER_TO_HTML_ENTITY_WITH_AMPERSAND_RE.sub( + cls._substitute_html_entity, s + ) + + @classmethod + def substitute_html5(cls, s: str) -> str: + """Replace certain Unicode characters with named HTML entities + using HTML5 rules. + + Specifically, this method is much less aggressive about + escaping ampersands than substitute_html. Only ambiguous + ampersands are escaped, per the HTML5 standard: + + "An ambiguous ampersand is a U+0026 AMPERSAND character (&) + that is followed by one or more ASCII alphanumerics, followed + by a U+003B SEMICOLON character (;), where these characters do + not match any of the names given in the named character + references section." + + Unlike substitute_html5_raw, this method assumes HTML entities + were converted to Unicode characters on the way in, as + Beautiful Soup does. By the time Beautiful Soup does its work, + the only ambiguous ampersands that need to be escaped are the + ones that were escaped in the original markup when mentioning + HTML entities. + + :param s: The string to be modified. + :return: The string with some Unicode characters replaced with + HTML entities. + """ + # First, escape any HTML entities found in the markup. + s = cls.ANY_ENTITY_RE.sub(cls._escape_entity_name, s) + + # Next, convert any appropriate characters to unescaped HTML entities. + s = cls.CHARACTER_TO_HTML_ENTITY_RE.sub(cls._substitute_html_entity, s) + + return s + + @classmethod + def substitute_html5_raw(cls, s: str) -> str: + """Replace certain Unicode characters with named HTML entities + using HTML5 rules. + + substitute_html5_raw is similar to substitute_html5 but it is + designed for standalone use (whereas substitute_html5 is + designed for use with Beautiful Soup). + + :param s: The string to be modified. + :return: The string with some Unicode characters replaced with + HTML entities. + """ + # First, escape the ampersand for anything that looks like an + # entity but isn't in the list of recognized entities. All other + # ampersands can be left alone. + s = cls.ANY_ENTITY_RE.sub(cls._escape_unrecognized_entity_name, s) + + # Then, convert a range of Unicode characters to unescaped + # HTML entities. + s = cls.CHARACTER_TO_HTML_ENTITY_RE.sub(cls._substitute_html_entity, s) + + return s + + +EntitySubstitution._populate_class_variables() + + +class EncodingDetector: + """This class is capable of guessing a number of possible encodings + for a bytestring. + + Order of precedence: + + 1. Encodings you specifically tell EncodingDetector to try first + (the ``known_definite_encodings`` argument to the constructor). + + 2. An encoding determined by sniffing the document's byte-order mark. + + 3. Encodings you specifically tell EncodingDetector to try if + byte-order mark sniffing fails (the ``user_encodings`` argument to the + constructor). + + 4. An encoding declared within the bytestring itself, either in an + XML declaration (if the bytestring is to be interpreted as an XML + document), or in a tag (if the bytestring is to be + interpreted as an HTML document.) + + 5. An encoding detected through textual analysis by chardet, + cchardet, or a similar external library. + + 6. UTF-8. + + 7. Windows-1252. + + :param markup: Some markup in an unknown encoding. + + :param known_definite_encodings: When determining the encoding + of ``markup``, these encodings will be tried first, in + order. In HTML terms, this corresponds to the "known + definite encoding" step defined in `section 13.2.3.1 of the HTML standard `_. + + :param user_encodings: These encodings will be tried after the + ``known_definite_encodings`` have been tried and failed, and + after an attempt to sniff the encoding by looking at a + byte order mark has failed. In HTML terms, this + corresponds to the step "user has explicitly instructed + the user agent to override the document's character + encoding", defined in `section 13.2.3.2 of the HTML standard `_. + + :param override_encodings: A **deprecated** alias for + ``known_definite_encodings``. Any encodings here will be tried + immediately after the encodings in + ``known_definite_encodings``. + + :param is_html: If True, this markup is considered to be + HTML. Otherwise it's assumed to be XML. + + :param exclude_encodings: These encodings will not be tried, + even if they otherwise would be. + + """ + + def __init__( + self, + markup: bytes, + known_definite_encodings: Optional[_Encodings] = None, + is_html: Optional[bool] = False, + exclude_encodings: Optional[_Encodings] = None, + user_encodings: Optional[_Encodings] = None, + override_encodings: Optional[_Encodings] = None, + ): + self.known_definite_encodings = list(known_definite_encodings or []) + if override_encodings: + warnings.warn( + "The 'override_encodings' argument was deprecated in 4.10.0. Use 'known_definite_encodings' instead.", + DeprecationWarning, + stacklevel=3, + ) + self.known_definite_encodings += override_encodings + self.user_encodings = user_encodings or [] + exclude_encodings = exclude_encodings or [] + self.exclude_encodings = set([x.lower() for x in exclude_encodings]) + self.chardet_encoding = None + self.is_html = False if is_html is None else is_html + self.declared_encoding: Optional[str] = None + + # First order of business: strip a byte-order mark. + self.markup, self.sniffed_encoding = self.strip_byte_order_mark(markup) + + known_definite_encodings: _Encodings + user_encodings: _Encodings + exclude_encodings: _Encodings + chardet_encoding: Optional[_Encoding] + is_html: bool + declared_encoding: Optional[_Encoding] + markup: bytes + sniffed_encoding: Optional[_Encoding] + + def _usable(self, encoding: Optional[_Encoding], tried: Set[_Encoding]) -> bool: + """Should we even bother to try this encoding? + + :param encoding: Name of an encoding. + :param tried: Encodings that have already been tried. This + will be modified as a side effect. + """ + if encoding is None: + return False + encoding = encoding.lower() + if encoding in self.exclude_encodings: + return False + if encoding not in tried: + tried.add(encoding) + return True + return False + + @property + def encodings(self) -> Iterator[_Encoding]: + """Yield a number of encodings that might work for this markup. + + :yield: A sequence of strings. Each is the name of an encoding + that *might* work to convert a bytestring into Unicode. + """ + tried: Set[_Encoding] = set() + + # First, try the known definite encodings + for e in self.known_definite_encodings: + if self._usable(e, tried): + yield e + + # Did the document originally start with a byte-order mark + # that indicated its encoding? + if self.sniffed_encoding is not None and self._usable( + self.sniffed_encoding, tried + ): + yield self.sniffed_encoding + + # Sniffing the byte-order mark did nothing; try the user + # encodings. + for e in self.user_encodings: + if self._usable(e, tried): + yield e + + # Look within the document for an XML or HTML encoding + # declaration. + if self.declared_encoding is None: + self.declared_encoding = self.find_declared_encoding( + self.markup, self.is_html + ) + if self.declared_encoding is not None and self._usable( + self.declared_encoding, tried + ): + yield self.declared_encoding + + # Use third-party character set detection to guess at the + # encoding. + if self.chardet_encoding is None: + self.chardet_encoding = _chardet_dammit(self.markup) + if self.chardet_encoding is not None and self._usable( + self.chardet_encoding, tried + ): + yield self.chardet_encoding + + # As a last-ditch effort, try utf-8 and windows-1252. + for e in ("utf-8", "windows-1252"): + if self._usable(e, tried): + yield e + + @classmethod + def strip_byte_order_mark(cls, data: bytes) -> Tuple[bytes, Optional[_Encoding]]: + """If a byte-order mark is present, strip it and return the encoding it implies. + + :param data: A bytestring that may or may not begin with a + byte-order mark. + + :return: A 2-tuple (data stripped of byte-order mark, encoding implied by byte-order mark) + """ + encoding = None + if isinstance(data, str): + # Unicode data cannot have a byte-order mark. + return data, encoding + if ( + (len(data) >= 4) + and (data[:2] == b"\xfe\xff") + and (data[2:4] != b"\x00\x00") + ): + encoding = "utf-16be" + data = data[2:] + elif ( + (len(data) >= 4) + and (data[:2] == b"\xff\xfe") + and (data[2:4] != b"\x00\x00") + ): + encoding = "utf-16le" + data = data[2:] + elif data[:3] == b"\xef\xbb\xbf": + encoding = "utf-8" + data = data[3:] + elif data[:4] == b"\x00\x00\xfe\xff": + encoding = "utf-32be" + data = data[4:] + elif data[:4] == b"\xff\xfe\x00\x00": + encoding = "utf-32le" + data = data[4:] + return data, encoding + + @classmethod + def find_declared_encoding( + cls, + markup: Union[bytes, str], + is_html: bool = False, + search_entire_document: bool = False, + ) -> Optional[_Encoding]: + """Given a document, tries to find an encoding declared within the + text of the document itself. + + An XML encoding is declared at the beginning of the document. + + An HTML encoding is declared in a tag, hopefully near the + beginning of the document. + + :param markup: Some markup. + :param is_html: If True, this markup is considered to be HTML. Otherwise + it's assumed to be XML. + :param search_entire_document: Since an encoding is supposed + to declared near the beginning of the document, most of + the time it's only necessary to search a few kilobytes of + data. Set this to True to force this method to search the + entire document. + :return: The declared encoding, if one is found. + """ + if search_entire_document: + xml_endpos = html_endpos = len(markup) + else: + xml_endpos = 1024 + html_endpos = max(2048, int(len(markup) * 0.05)) + + if isinstance(markup, bytes): + res = encoding_res[bytes] + else: + res = encoding_res[str] + + xml_re = res["xml"] + html_re = res["html"] + declared_encoding: Optional[_Encoding] = None + declared_encoding_match = xml_re.search(markup, endpos=xml_endpos) + if not declared_encoding_match and is_html: + declared_encoding_match = html_re.search(markup, endpos=html_endpos) + if declared_encoding_match is not None: + declared_encoding = declared_encoding_match.groups()[0] + if declared_encoding: + if isinstance(declared_encoding, bytes): + declared_encoding = declared_encoding.decode("ascii", "replace") + return declared_encoding.lower() + return None + + +class UnicodeDammit: + """A class for detecting the encoding of a bytestring containing an + HTML or XML document, and decoding it to Unicode. If the source + encoding is windows-1252, `UnicodeDammit` can also replace + Microsoft smart quotes with their HTML or XML equivalents. + + :param markup: HTML or XML markup in an unknown encoding. + + :param known_definite_encodings: When determining the encoding + of ``markup``, these encodings will be tried first, in + order. In HTML terms, this corresponds to the "known + definite encoding" step defined in `section 13.2.3.1 of the HTML standard `_. + + :param user_encodings: These encodings will be tried after the + ``known_definite_encodings`` have been tried and failed, and + after an attempt to sniff the encoding by looking at a + byte order mark has failed. In HTML terms, this + corresponds to the step "user has explicitly instructed + the user agent to override the document's character + encoding", defined in `section 13.2.3.2 of the HTML standard `_. + + :param override_encodings: A **deprecated** alias for + ``known_definite_encodings``. Any encodings here will be tried + immediately after the encodings in + ``known_definite_encodings``. + + :param smart_quotes_to: By default, Microsoft smart quotes will, + like all other characters, be converted to Unicode + characters. Setting this to ``ascii`` will convert them to ASCII + quotes instead. Setting it to ``xml`` will convert them to XML + entity references, and setting it to ``html`` will convert them + to HTML entity references. + + :param is_html: If True, ``markup`` is treated as an HTML + document. Otherwise it's treated as an XML document. + + :param exclude_encodings: These encodings will not be considered, + even if the sniffing code thinks they might make sense. + + """ + + def __init__( + self, + markup: bytes, + known_definite_encodings: Optional[_Encodings] = [], + smart_quotes_to: Optional[Literal["ascii", "xml", "html"]] = None, + is_html: bool = False, + exclude_encodings: Optional[_Encodings] = [], + user_encodings: Optional[_Encodings] = None, + override_encodings: Optional[_Encodings] = None, + ): + self.smart_quotes_to = smart_quotes_to + self.tried_encodings = [] + self.contains_replacement_characters = False + self.is_html = is_html + self.log = getLogger(__name__) + self.detector = EncodingDetector( + markup, + known_definite_encodings, + is_html, + exclude_encodings, + user_encodings, + override_encodings, + ) + + # Short-circuit if the data is in Unicode to begin with. + if isinstance(markup, str): + self.markup = markup.encode("utf8") + self.unicode_markup = markup + self.original_encoding = None + return + + # The encoding detector may have stripped a byte-order mark. + # Use the stripped markup from this point on. + self.markup = self.detector.markup + + u = None + for encoding in self.detector.encodings: + markup = self.detector.markup + u = self._convert_from(encoding) + if u is not None: + break + + if not u: + # None of the encodings worked. As an absolute last resort, + # try them again with character replacement. + + for encoding in self.detector.encodings: + if encoding != "ascii": + u = self._convert_from(encoding, "replace") + if u is not None: + self.log.warning( + "Some characters could not be decoded, and were " + "replaced with REPLACEMENT CHARACTER." + ) + + self.contains_replacement_characters = True + break + + # If none of that worked, we could at this point force it to + # ASCII, but that would destroy so much data that I think + # giving up is better. + # + # Note that this is extremely unlikely, probably impossible, + # because the "replace" strategy is so powerful. Even running + # the Python binary through Unicode, Dammit gives you Unicode, + # albeit Unicode riddled with REPLACEMENT CHARACTER. + if u is None: + self.original_encoding = None + self.unicode_markup = None + else: + self.unicode_markup = u + + #: The original markup, before it was converted to Unicode. + #: This is not necessarily the same as what was passed in to the + #: constructor, since any byte-order mark will be stripped. + markup: bytes + + #: The Unicode version of the markup, following conversion. This + #: is set to None if there was simply no way to convert the + #: bytestring to Unicode (as with binary data). + unicode_markup: Optional[str] + + #: This is True if `UnicodeDammit.unicode_markup` contains + #: U+FFFD REPLACEMENT_CHARACTER characters which were not present + #: in `UnicodeDammit.markup`. These mark character sequences that + #: could not be represented in Unicode. + contains_replacement_characters: bool + + #: Unicode, Dammit's best guess as to the original character + #: encoding of `UnicodeDammit.markup`. + original_encoding: Optional[_Encoding] + + #: The strategy used to handle Microsoft smart quotes. + smart_quotes_to: Optional[str] + + #: The (encoding, error handling strategy) 2-tuples that were used to + #: try and convert the markup to Unicode. + tried_encodings: List[Tuple[_Encoding, str]] + + log: Logger #: :meta private: + + def _sub_ms_char(self, match: re.Match) -> bytes: + """Changes a MS smart quote character to an XML or HTML + entity, or an ASCII character. + + TODO: Since this is only used to convert smart quotes, it + could be simplified, and MS_CHARS_TO_ASCII made much less + parochial. + """ + orig: bytes = match.group(1) + sub: bytes + if self.smart_quotes_to == "ascii": + if orig in self.MS_CHARS_TO_ASCII: + sub = self.MS_CHARS_TO_ASCII[orig].encode() + else: + # Shouldn't happen; substitute the character + # with itself. + sub = orig + else: + if orig in self.MS_CHARS: + substitutions = self.MS_CHARS[orig] + if type(substitutions) is tuple: + if self.smart_quotes_to == "xml": + sub = b"&#x" + substitutions[1].encode() + b";" + else: + sub = b"&" + substitutions[0].encode() + b";" + else: + substitutions = cast(str, substitutions) + sub = substitutions.encode() + else: + # Shouldn't happen; substitute the character + # for itself. + sub = orig + return sub + + #: This dictionary maps commonly seen values for "charset" in HTML + #: meta tags to the corresponding Python codec names. It only covers + #: values that aren't in Python's aliases and can't be determined + #: by the heuristics in `find_codec`. + #: + #: :meta hide-value: + CHARSET_ALIASES: Dict[str, _Encoding] = { + "macintosh": "mac-roman", + "x-sjis": "shift-jis", + } + + #: A list of encodings that tend to contain Microsoft smart quotes. + #: + #: :meta hide-value: + ENCODINGS_WITH_SMART_QUOTES: _Encodings = [ + "windows-1252", + "iso-8859-1", + "iso-8859-2", + ] + + def _convert_from( + self, proposed: _Encoding, errors: str = "strict" + ) -> Optional[str]: + """Attempt to convert the markup to the proposed encoding. + + :param proposed: The name of a character encoding. + :param errors: An error handling strategy, used when calling `str`. + :return: The converted markup, or `None` if the proposed + encoding/error handling strategy didn't work. + """ + lookup_result = self.find_codec(proposed) + if lookup_result is None or (lookup_result, errors) in self.tried_encodings: + return None + proposed = lookup_result + self.tried_encodings.append((proposed, errors)) + markup = self.markup + # Convert smart quotes to HTML if coming from an encoding + # that might have them. + if ( + self.smart_quotes_to is not None + and proposed in self.ENCODINGS_WITH_SMART_QUOTES + ): + smart_quotes_re = b"([\x80-\x9f])" + smart_quotes_compiled = re.compile(smart_quotes_re) + markup = smart_quotes_compiled.sub(self._sub_ms_char, markup) + + try: + # print("Trying to convert document to %s (errors=%s)" % ( + # proposed, errors)) + u = self._to_unicode(markup, proposed, errors) + self.unicode_markup = u + self.original_encoding = proposed + except Exception: + # print("That didn't work!") + # print(e) + return None + # print("Correct encoding: %s" % proposed) + return self.unicode_markup + + def _to_unicode( + self, data: bytes, encoding: _Encoding, errors: str = "strict" + ) -> str: + """Given a bytestring and its encoding, decodes the string into Unicode. + + :param encoding: The name of an encoding. + :param errors: An error handling strategy, used when calling `str`. + """ + return str(data, encoding, errors) + + @property + def declared_html_encoding(self) -> Optional[_Encoding]: + """If the markup is an HTML document, returns the encoding, if any, + declared *inside* the document. + """ + if not self.is_html: + return None + return self.detector.declared_encoding + + def find_codec(self, charset: _Encoding) -> Optional[str]: + """Look up the Python codec corresponding to a given character set. + + :param charset: The name of a character set. + :return: The name of a Python codec. + """ + value = ( + self._codec(self.CHARSET_ALIASES.get(charset, charset)) + or (charset and self._codec(charset.replace("-", ""))) + or (charset and self._codec(charset.replace("-", "_"))) + or (charset and charset.lower()) + or charset + ) + if value: + return value.lower() + return None + + def _codec(self, charset: _Encoding) -> Optional[str]: + if not charset: + return charset + codec = None + try: + codecs.lookup(charset) + codec = charset + except (LookupError, ValueError): + pass + return codec + + #: A partial mapping of ISO-Latin-1 to HTML entities/XML numeric entities. + #: + #: :meta hide-value: + MS_CHARS: Dict[bytes, Union[str, Tuple[str, str]]] = { + b"\x80": ("euro", "20AC"), + b"\x81": " ", + b"\x82": ("sbquo", "201A"), + b"\x83": ("fnof", "192"), + b"\x84": ("bdquo", "201E"), + b"\x85": ("hellip", "2026"), + b"\x86": ("dagger", "2020"), + b"\x87": ("Dagger", "2021"), + b"\x88": ("circ", "2C6"), + b"\x89": ("permil", "2030"), + b"\x8a": ("Scaron", "160"), + b"\x8b": ("lsaquo", "2039"), + b"\x8c": ("OElig", "152"), + b"\x8d": "?", + b"\x8e": ("#x17D", "17D"), + b"\x8f": "?", + b"\x90": "?", + b"\x91": ("lsquo", "2018"), + b"\x92": ("rsquo", "2019"), + b"\x93": ("ldquo", "201C"), + b"\x94": ("rdquo", "201D"), + b"\x95": ("bull", "2022"), + b"\x96": ("ndash", "2013"), + b"\x97": ("mdash", "2014"), + b"\x98": ("tilde", "2DC"), + b"\x99": ("trade", "2122"), + b"\x9a": ("scaron", "161"), + b"\x9b": ("rsaquo", "203A"), + b"\x9c": ("oelig", "153"), + b"\x9d": "?", + b"\x9e": ("#x17E", "17E"), + b"\x9f": ("Yuml", ""), + } + + #: A parochial partial mapping of ISO-Latin-1 to ASCII. Contains + #: horrors like stripping diacritical marks to turn á into a, but also + #: contains non-horrors like turning “ into ". + #: + #: Seriously, don't use this for anything other than removing smart + #: quotes. + #: + #: :meta private: + MS_CHARS_TO_ASCII: Dict[bytes, str] = { + b"\x80": "EUR", + b"\x81": " ", + b"\x82": ",", + b"\x83": "f", + b"\x84": ",,", + b"\x85": "...", + b"\x86": "+", + b"\x87": "++", + b"\x88": "^", + b"\x89": "%", + b"\x8a": "S", + b"\x8b": "<", + b"\x8c": "OE", + b"\x8d": "?", + b"\x8e": "Z", + b"\x8f": "?", + b"\x90": "?", + b"\x91": "'", + b"\x92": "'", + b"\x93": '"', + b"\x94": '"', + b"\x95": "*", + b"\x96": "-", + b"\x97": "--", + b"\x98": "~", + b"\x99": "(TM)", + b"\x9a": "s", + b"\x9b": ">", + b"\x9c": "oe", + b"\x9d": "?", + b"\x9e": "z", + b"\x9f": "Y", + b"\xa0": " ", + b"\xa1": "!", + b"\xa2": "c", + b"\xa3": "GBP", + b"\xa4": "$", # This approximation is especially parochial--this is the + # generic currency symbol. + b"\xa5": "YEN", + b"\xa6": "|", + b"\xa7": "S", + b"\xa8": "..", + b"\xa9": "", + b"\xaa": "(th)", + b"\xab": "<<", + b"\xac": "!", + b"\xad": " ", + b"\xae": "(R)", + b"\xaf": "-", + b"\xb0": "o", + b"\xb1": "+-", + b"\xb2": "2", + b"\xb3": "3", + b"\xb4": "'", + b"\xb5": "u", + b"\xb6": "P", + b"\xb7": "*", + b"\xb8": ",", + b"\xb9": "1", + b"\xba": "(th)", + b"\xbb": ">>", + b"\xbc": "1/4", + b"\xbd": "1/2", + b"\xbe": "3/4", + b"\xbf": "?", + b"\xc0": "A", + b"\xc1": "A", + b"\xc2": "A", + b"\xc3": "A", + b"\xc4": "A", + b"\xc5": "A", + b"\xc6": "AE", + b"\xc7": "C", + b"\xc8": "E", + b"\xc9": "E", + b"\xca": "E", + b"\xcb": "E", + b"\xcc": "I", + b"\xcd": "I", + b"\xce": "I", + b"\xcf": "I", + b"\xd0": "D", + b"\xd1": "N", + b"\xd2": "O", + b"\xd3": "O", + b"\xd4": "O", + b"\xd5": "O", + b"\xd6": "O", + b"\xd7": "*", + b"\xd8": "O", + b"\xd9": "U", + b"\xda": "U", + b"\xdb": "U", + b"\xdc": "U", + b"\xdd": "Y", + b"\xde": "b", + b"\xdf": "B", + b"\xe0": "a", + b"\xe1": "a", + b"\xe2": "a", + b"\xe3": "a", + b"\xe4": "a", + b"\xe5": "a", + b"\xe6": "ae", + b"\xe7": "c", + b"\xe8": "e", + b"\xe9": "e", + b"\xea": "e", + b"\xeb": "e", + b"\xec": "i", + b"\xed": "i", + b"\xee": "i", + b"\xef": "i", + b"\xf0": "o", + b"\xf1": "n", + b"\xf2": "o", + b"\xf3": "o", + b"\xf4": "o", + b"\xf5": "o", + b"\xf6": "o", + b"\xf7": "/", + b"\xf8": "o", + b"\xf9": "u", + b"\xfa": "u", + b"\xfb": "u", + b"\xfc": "u", + b"\xfd": "y", + b"\xfe": "b", + b"\xff": "y", + } + + #: A map used when removing rogue Windows-1252/ISO-8859-1 + #: characters in otherwise UTF-8 documents. Also used when a + #: numeric character entity has been incorrectly encoded using the + #: character's Windows-1252 encoding. + #: + #: Note that \\x81, \\x8d, \\x8f, \\x90, and \\x9d are undefined in + #: Windows-1252. + #: + #: :meta hide-value: + WINDOWS_1252_TO_UTF8: Dict[int, bytes] = { + 0x80: b"\xe2\x82\xac", # € + 0x82: b"\xe2\x80\x9a", # ‚ + 0x83: b"\xc6\x92", # ƒ + 0x84: b"\xe2\x80\x9e", # „ + 0x85: b"\xe2\x80\xa6", # … + 0x86: b"\xe2\x80\xa0", # † + 0x87: b"\xe2\x80\xa1", # ‡ + 0x88: b"\xcb\x86", # ˆ + 0x89: b"\xe2\x80\xb0", # ‰ + 0x8A: b"\xc5\xa0", # Š + 0x8B: b"\xe2\x80\xb9", # ‹ + 0x8C: b"\xc5\x92", # Œ + 0x8E: b"\xc5\xbd", # Ž + 0x91: b"\xe2\x80\x98", # ‘ + 0x92: b"\xe2\x80\x99", # ’ + 0x93: b"\xe2\x80\x9c", # “ + 0x94: b"\xe2\x80\x9d", # ” + 0x95: b"\xe2\x80\xa2", # • + 0x96: b"\xe2\x80\x93", # – + 0x97: b"\xe2\x80\x94", # — + 0x98: b"\xcb\x9c", # ˜ + 0x99: b"\xe2\x84\xa2", # ™ + 0x9A: b"\xc5\xa1", # š + 0x9B: b"\xe2\x80\xba", # › + 0x9C: b"\xc5\x93", # œ + 0x9E: b"\xc5\xbe", # ž + 0x9F: b"\xc5\xb8", # Ÿ + 0xA0: b"\xc2\xa0", # + 0xA1: b"\xc2\xa1", # ¡ + 0xA2: b"\xc2\xa2", # ¢ + 0xA3: b"\xc2\xa3", # £ + 0xA4: b"\xc2\xa4", # ¤ + 0xA5: b"\xc2\xa5", # ¥ + 0xA6: b"\xc2\xa6", # ¦ + 0xA7: b"\xc2\xa7", # § + 0xA8: b"\xc2\xa8", # ¨ + 0xA9: b"\xc2\xa9", # © + 0xAA: b"\xc2\xaa", # ª + 0xAB: b"\xc2\xab", # « + 0xAC: b"\xc2\xac", # ¬ + 0xAD: b"\xc2\xad", # ­ + 0xAE: b"\xc2\xae", # ® + 0xAF: b"\xc2\xaf", # ¯ + 0xB0: b"\xc2\xb0", # ° + 0xB1: b"\xc2\xb1", # ± + 0xB2: b"\xc2\xb2", # ² + 0xB3: b"\xc2\xb3", # ³ + 0xB4: b"\xc2\xb4", # ´ + 0xB5: b"\xc2\xb5", # µ + 0xB6: b"\xc2\xb6", # ¶ + 0xB7: b"\xc2\xb7", # · + 0xB8: b"\xc2\xb8", # ¸ + 0xB9: b"\xc2\xb9", # ¹ + 0xBA: b"\xc2\xba", # º + 0xBB: b"\xc2\xbb", # » + 0xBC: b"\xc2\xbc", # ¼ + 0xBD: b"\xc2\xbd", # ½ + 0xBE: b"\xc2\xbe", # ¾ + 0xBF: b"\xc2\xbf", # ¿ + 0xC0: b"\xc3\x80", # À + 0xC1: b"\xc3\x81", # Á + 0xC2: b"\xc3\x82", #  + 0xC3: b"\xc3\x83", # à + 0xC4: b"\xc3\x84", # Ä + 0xC5: b"\xc3\x85", # Å + 0xC6: b"\xc3\x86", # Æ + 0xC7: b"\xc3\x87", # Ç + 0xC8: b"\xc3\x88", # È + 0xC9: b"\xc3\x89", # É + 0xCA: b"\xc3\x8a", # Ê + 0xCB: b"\xc3\x8b", # Ë + 0xCC: b"\xc3\x8c", # Ì + 0xCD: b"\xc3\x8d", # Í + 0xCE: b"\xc3\x8e", # Î + 0xCF: b"\xc3\x8f", # Ï + 0xD0: b"\xc3\x90", # Ð + 0xD1: b"\xc3\x91", # Ñ + 0xD2: b"\xc3\x92", # Ò + 0xD3: b"\xc3\x93", # Ó + 0xD4: b"\xc3\x94", # Ô + 0xD5: b"\xc3\x95", # Õ + 0xD6: b"\xc3\x96", # Ö + 0xD7: b"\xc3\x97", # × + 0xD8: b"\xc3\x98", # Ø + 0xD9: b"\xc3\x99", # Ù + 0xDA: b"\xc3\x9a", # Ú + 0xDB: b"\xc3\x9b", # Û + 0xDC: b"\xc3\x9c", # Ü + 0xDD: b"\xc3\x9d", # Ý + 0xDE: b"\xc3\x9e", # Þ + 0xDF: b"\xc3\x9f", # ß + 0xE0: b"\xc3\xa0", # à + 0xE1: b"\xa1", # á + 0xE2: b"\xc3\xa2", # â + 0xE3: b"\xc3\xa3", # ã + 0xE4: b"\xc3\xa4", # ä + 0xE5: b"\xc3\xa5", # å + 0xE6: b"\xc3\xa6", # æ + 0xE7: b"\xc3\xa7", # ç + 0xE8: b"\xc3\xa8", # è + 0xE9: b"\xc3\xa9", # é + 0xEA: b"\xc3\xaa", # ê + 0xEB: b"\xc3\xab", # ë + 0xEC: b"\xc3\xac", # ì + 0xED: b"\xc3\xad", # í + 0xEE: b"\xc3\xae", # î + 0xEF: b"\xc3\xaf", # ï + 0xF0: b"\xc3\xb0", # ð + 0xF1: b"\xc3\xb1", # ñ + 0xF2: b"\xc3\xb2", # ò + 0xF3: b"\xc3\xb3", # ó + 0xF4: b"\xc3\xb4", # ô + 0xF5: b"\xc3\xb5", # õ + 0xF6: b"\xc3\xb6", # ö + 0xF7: b"\xc3\xb7", # ÷ + 0xF8: b"\xc3\xb8", # ø + 0xF9: b"\xc3\xb9", # ù + 0xFA: b"\xc3\xba", # ú + 0xFB: b"\xc3\xbb", # û + 0xFC: b"\xc3\xbc", # ü + 0xFD: b"\xc3\xbd", # ý + 0xFE: b"\xc3\xbe", # þ + 0xFF: b"\xc3\xbf", # ÿ + } + + #: :meta private + # Note that this isn't all Unicode noncharacters, just the noncontiguous ones that need to be listed. + # + # "A noncharacter is a code point that is in the range + # U+FDD0 to U+FDEF, inclusive, or U+FFFE, U+FFFF, U+1FFFE, + # U+1FFFF, U+2FFFE, U+2FFFF, U+3FFFE, U+3FFFF, U+4FFFE, + # U+4FFFF, U+5FFFE, U+5FFFF, U+6FFFE, U+6FFFF, U+7FFFE, + # U+7FFFF, U+8FFFE, U+8FFFF, U+9FFFE, U+9FFFF, U+AFFFE, + # U+AFFFF, U+BFFFE, U+BFFFF, U+CFFFE, U+CFFFF, U+DFFFE, + # U+DFFFF, U+EFFFE, U+EFFFF, U+FFFFE, U+FFFFF, U+10FFFE, + # or U+10FFFF." + ENUMERATED_NONCHARACTERS: Set[int] = set([0xfffe, 0xffff, + 0x1fffe, 0x1ffff, + 0x2fffe, 0x2ffff, + 0x3fffe, 0x3ffff, + 0x4fffe, 0x4ffff, + 0x5fffe, 0x5ffff, + 0x6fffe, 0x6ffff, + 0x7fffe, 0x7ffff, + 0x8fffe, 0x8ffff, + 0x9fffe, 0x9ffff, + 0xafffe, 0xaffff, + 0xbfffe, 0xbffff, + 0xcfffe, 0xcffff, + 0xdfffe, 0xdffff, + 0xefffe, 0xeffff, + 0xffffe, 0xfffff, + 0x10fffe, 0x10ffff]) + + #: :meta private: + MULTIBYTE_MARKERS_AND_SIZES: List[Tuple[int, int, int]] = [ + (0xC2, 0xDF, 2), # 2-byte characters start with a byte C2-DF + (0xE0, 0xEF, 3), # 3-byte characters start with E0-EF + (0xF0, 0xF4, 4), # 4-byte characters start with F0-F4 + ] + + #: :meta private: + FIRST_MULTIBYTE_MARKER: int = MULTIBYTE_MARKERS_AND_SIZES[0][0] + + #: :meta private: + LAST_MULTIBYTE_MARKER: int = MULTIBYTE_MARKERS_AND_SIZES[-1][1] + + @classmethod + def numeric_character_reference(cls, numeric:int) -> Tuple[str, bool]: + """This (mostly) implements the algorithm described in "Numeric character + reference end state" from the HTML spec: + https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state + + The algorithm is designed to convert numeric character references like "☃" + to Unicode characters like "☃". + + :return: A 2-tuple (character, replaced). `character` is the Unicode + character corresponding to the numeric reference and `replaced` is + whether or not an unresolvable character was replaced with REPLACEMENT + CHARACTER. + """ + replacement = "\ufffd" + + if numeric == 0x00: + # "If the number is 0x00, then this is a + # null-character-reference parse error. Set the character + # reference code to 0xFFFD." + return replacement, True + + if numeric > 0x10ffff: + # "If the number is greater than 0x10FFFF, then this is a + # character-reference-outside-unicode-range parse + # error. Set the character reference code to 0xFFFD." + return replacement, True + + if numeric >= 0xd800 and numeric <= 0xdfff: + # "If the number is a surrogate, then this is a + # surrogate-character-reference parse error. Set the + # character reference code to 0xFFFD." + return replacement, True + + if (numeric >= 0xfdd0 and numeric <= 0xfdef) or numeric in cls.ENUMERATED_NONCHARACTERS: + # "If the number is a noncharacter, then this is a + # noncharacter-character-reference parse error." + # + # "The parser resolves such character references as-is." + # + # I'm not sure what "as-is" means but I think it means that we act + # like there was no error condition. + return chr(numeric), False + + # "If the number is 0x0D, or a control that's not ASCII whitespace, + # then this is a control-character-reference parse error." + # + # "A control is a C0 control or a code point in the range + # U+007F DELETE to U+009F APPLICATION PROGRAM COMMAND, + # inclusive." + # + # "A C0 control is a code point in the range U+0000 NULL to U+001F INFORMATION SEPARATOR ONE, inclusive." + # + # "The parser resolves such character references as-is except C1 control references that are replaced." + + # First, let's replace the control references that can be replaced. + if numeric >= 0x80 and numeric <= 0x9f and numeric in cls.WINDOWS_1252_TO_UTF8: + # "If the number is one of the numbers in the first column of the + # following table, then find the row with that number in the first + # column, and set the character reference code to the number in the + # second column of that row." + # + # This is an attempt to catch characters that were encoded to numeric + # entities using their Windows-1252 encodings rather than their UTF-8 + # encodings. + return cls.WINDOWS_1252_TO_UTF8[numeric].decode("utf8"), False + + # Now all that's left are references that should be resolved as-is. This + # is also the default path for non-weird character references. + try: + return chr(numeric), False + except (ValueError, OverflowError): + # This shouldn't happen, since these cases should have been handled + # above, but if it does, return REPLACEMENT CHARACTER + return replacement, True + + @classmethod + def detwingle( + cls, + in_bytes: bytes, + main_encoding: _Encoding = "utf8", + embedded_encoding: _Encoding = "windows-1252", + ) -> bytes: + """Fix characters from one encoding embedded in some other encoding. + + Currently the only situation supported is Windows-1252 (or its + subset ISO-8859-1), embedded in UTF-8. + + :param in_bytes: A bytestring that you suspect contains + characters from multiple encodings. Note that this *must* + be a bytestring. If you've already converted the document + to Unicode, you're too late. + :param main_encoding: The primary encoding of ``in_bytes``. + :param embedded_encoding: The encoding that was used to embed characters + in the main document. + :return: A bytestring similar to ``in_bytes``, in which + ``embedded_encoding`` characters have been converted to + their ``main_encoding`` equivalents. + """ + if embedded_encoding.replace("_", "-").lower() not in ( + "windows-1252", + "windows_1252", + ): + raise NotImplementedError( + "Windows-1252 and ISO-8859-1 are the only currently supported " + "embedded encodings." + ) + + if main_encoding.lower() not in ("utf8", "utf-8"): + raise NotImplementedError( + "UTF-8 is the only currently supported main encoding." + ) + + byte_chunks = [] + + chunk_start = 0 + pos = 0 + while pos < len(in_bytes): + byte = in_bytes[pos] + if byte >= cls.FIRST_MULTIBYTE_MARKER and byte <= cls.LAST_MULTIBYTE_MARKER: + # This is the start of a UTF-8 multibyte character. Skip + # to the end. + for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES: + if byte >= start and byte <= end: + pos += size + break + elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8: + # We found a Windows-1252 character! + # Save the string up to this point as a chunk. + byte_chunks.append(in_bytes[chunk_start:pos]) + + # Now translate the Windows-1252 character into UTF-8 + # and add it as another, one-byte chunk. + byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte]) + pos += 1 + chunk_start = pos + else: + # Go on to the next character. + pos += 1 + if chunk_start == 0: + # The string is unchanged. + return in_bytes + else: + # Store the final chunk. + byte_chunks.append(in_bytes[chunk_start:]) + return b"".join(byte_chunks) diff --git a/python/py313/Lib/site-packages/bs4/diagnose.py b/python/py313/Lib/site-packages/bs4/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..4d11239c472c4d9cfc55abf985df15591a39048c --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/diagnose.py @@ -0,0 +1,268 @@ +"""Diagnostic functions, mainly for use when doing tech support.""" + +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +import cProfile +from io import BytesIO +from html.parser import HTMLParser +import bs4 +from bs4 import BeautifulSoup, __version__ +from bs4.builder import builder_registry +from typing import ( + Any, + IO, + List, + Optional, + Tuple, + TYPE_CHECKING, +) + +if TYPE_CHECKING: + from bs4._typing import _IncomingMarkup + +import pstats +import random +import tempfile +import time +import traceback +import sys + + +def diagnose(data: "_IncomingMarkup") -> None: + """Diagnostic suite for isolating common problems. + + :param data: Some markup that needs to be explained. + :return: None; diagnostics are printed to standard output. + """ + print(("Diagnostic running on Beautiful Soup %s" % __version__)) + print(("Python version %s" % sys.version)) + + basic_parsers = ["html.parser", "html5lib", "lxml"] + for name in basic_parsers: + for builder in builder_registry.builders: + if name in builder.features: + break + else: + basic_parsers.remove(name) + print( + ("I noticed that %s is not installed. Installing it may help." % name) + ) + + if "lxml" in basic_parsers: + basic_parsers.append("lxml-xml") + try: + from lxml import etree # type:ignore + + print(("Found lxml version %s" % ".".join(map(str, etree.LXML_VERSION)))) + except ImportError: + print("lxml is not installed or couldn't be imported.") + + if "html5lib" in basic_parsers: + try: + import html5lib + + print(("Found html5lib version %s" % html5lib.__version__)) + except ImportError: + print("html5lib is not installed or couldn't be imported.") + + if hasattr(data, "read"): + data = data.read() + + for parser in basic_parsers: + print(("Trying to parse your markup with %s" % parser)) + success = False + try: + soup = BeautifulSoup(data, features=parser) + success = True + except Exception: + print(("%s could not parse the markup." % parser)) + traceback.print_exc() + if success: + print(("Here's what %s did with the markup:" % parser)) + print((soup.prettify())) + + print(("-" * 80)) + + +def lxml_trace(data: "_IncomingMarkup", html: bool = True, **kwargs: Any) -> None: + """Print out the lxml events that occur during parsing. + + This lets you see how lxml parses a document when no Beautiful + Soup code is running. You can use this to determine whether + an lxml-specific problem is in Beautiful Soup's lxml tree builders + or in lxml itself. + + :param data: Some markup. + :param html: If True, markup will be parsed with lxml's HTML parser. + if False, lxml's XML parser will be used. + """ + from lxml import etree + + recover = kwargs.pop("recover", True) + if isinstance(data, str): + data = data.encode("utf8") + if not isinstance(data, IO): + reader = BytesIO(data) + for event, element in etree.iterparse(reader, html=html, recover=recover, **kwargs): + print(("%s, %4s, %s" % (event, element.tag, element.text))) + + +class AnnouncingParser(HTMLParser): + """Subclass of HTMLParser that announces parse events, without doing + anything else. + + You can use this to get a picture of how html.parser sees a given + document. The easiest way to do this is to call `htmlparser_trace`. + """ + + def _p(self, s: str) -> None: + print(s) + + def handle_starttag( + self, + name: str, + attrs: List[Tuple[str, Optional[str]]], + handle_empty_element: bool = True, + ) -> None: + self._p(f"{name} {attrs} START") + + def handle_endtag(self, name: str, check_already_closed: bool = True) -> None: + self._p("%s END" % name) + + def handle_data(self, data: str) -> None: + self._p("%s DATA" % data) + + def handle_charref(self, name: str) -> None: + self._p("%s CHARREF" % name) + + def handle_entityref(self, name: str) -> None: + self._p("%s ENTITYREF" % name) + + def handle_comment(self, data: str) -> None: + self._p("%s COMMENT" % data) + + def handle_decl(self, data: str) -> None: + self._p("%s DECL" % data) + + def unknown_decl(self, data: str) -> None: + self._p("%s UNKNOWN-DECL" % data) + + def handle_pi(self, data: str) -> None: + self._p("%s PI" % data) + + +def htmlparser_trace(data: str) -> None: + """Print out the HTMLParser events that occur during parsing. + + This lets you see how HTMLParser parses a document when no + Beautiful Soup code is running. + + :param data: Some markup. + """ + parser = AnnouncingParser() + parser.feed(data) + + +_vowels: str = "aeiou" +_consonants: str = "bcdfghjklmnpqrstvwxyz" + + +def rword(length: int = 5) -> str: + """Generate a random word-like string. + + :meta private: + """ + s = "" + for i in range(length): + if i % 2 == 0: + t = _consonants + else: + t = _vowels + s += random.choice(t) + return s + + +def rsentence(length: int = 4) -> str: + """Generate a random sentence-like string. + + :meta private: + """ + return " ".join(rword(random.randint(4, 9)) for i in range(length)) + + +def rdoc(num_elements: int = 1000) -> str: + """Randomly generate an invalid HTML document. + + :meta private: + """ + tag_names = ["p", "div", "span", "i", "b", "script", "table"] + elements = [] + for i in range(num_elements): + choice = random.randint(0, 3) + if choice == 0: + # New tag. + tag_name = random.choice(tag_names) + elements.append("<%s>" % tag_name) + elif choice == 1: + elements.append(rsentence(random.randint(1, 4))) + elif choice == 2: + # Close a tag. + tag_name = random.choice(tag_names) + elements.append("" % tag_name) + return "" + "\n".join(elements) + "" + + +def benchmark_parsers(num_elements: int = 100000) -> None: + """Very basic head-to-head performance benchmark.""" + print(("Comparative parser benchmark on Beautiful Soup %s" % __version__)) + data = rdoc(num_elements) + print(("Generated a large invalid HTML document (%d bytes)." % len(data))) + + for parser_name in ["lxml", ["lxml", "html"], "html5lib", "html.parser"]: + success = False + try: + a = time.time() + BeautifulSoup(data, parser_name) + b = time.time() + success = True + except Exception: + print(("%s could not parse the markup." % parser_name)) + traceback.print_exc() + if success: + print(("BS4+%s parsed the markup in %.2fs." % (parser_name, b - a))) + + from lxml import etree + + a = time.time() + etree.HTML(data) + b = time.time() + print(("Raw lxml parsed the markup in %.2fs." % (b - a))) + + import html5lib + + parser = html5lib.HTMLParser() + a = time.time() + parser.parse(data) + b = time.time() + print(("Raw html5lib parsed the markup in %.2fs." % (b - a))) + + +def profile(num_elements: int = 100000, parser: str = "lxml") -> None: + """Use Python's profiler on a randomly generated document.""" + filehandle = tempfile.NamedTemporaryFile() + filename = filehandle.name + + data = rdoc(num_elements) + vars = dict(bs4=bs4, data=data, parser=parser) + cProfile.runctx("bs4.BeautifulSoup(data, parser)", vars, vars, filename) + + stats = pstats.Stats(filename) + # stats.strip_dirs() + stats.sort_stats("cumulative") + stats.print_stats("_html5lib|bs4", 50) + + +# If this file is run as a script, standard input is diagnosed. +if __name__ == "__main__": + diagnose(sys.stdin.read()) diff --git a/python/py313/Lib/site-packages/bs4/element.py b/python/py313/Lib/site-packages/bs4/element.py new file mode 100644 index 0000000000000000000000000000000000000000..dd07d8ebcad653106cc1dc247740758525556023 --- /dev/null +++ b/python/py313/Lib/site-packages/bs4/element.py @@ -0,0 +1,3211 @@ +from __future__ import annotations + +# Use of this source code is governed by the MIT license. +__license__ = "MIT" + +import re +import warnings + +from bs4.css import CSS +from bs4._deprecation import ( + _deprecated, + _deprecated_alias, + _deprecated_function_alias, +) +from bs4.formatter import ( + Formatter, + HTMLFormatter, + XMLFormatter, +) +from bs4._warnings import AttributeResemblesVariableWarning + +from typing import ( + Any, + Callable, + Dict, + Generic, + Iterable, + Iterator, + List, + Mapping, + MutableSequence, + Optional, + Pattern, + Set, + TYPE_CHECKING, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) +from typing_extensions import ( + Self, + TypeAlias, +) + +if TYPE_CHECKING: + from bs4 import BeautifulSoup + from bs4.builder import TreeBuilder + from bs4.filter import ElementFilter + from bs4.formatter import ( + _EntitySubstitutionFunction, + _FormatterOrName, + ) + from bs4._typing import ( + _AtMostOneElement, + _AtMostOneTag, + _AtMostOneNavigableString, + _AttributeValue, + _AttributeValues, + _Encoding, + _InsertableElement, + _OneElement, + _QueryResults, + _RawOrProcessedAttributeValues, + _StrainableElement, + _StrainableAttribute, + _StrainableAttributes, + _StrainableString, + _SomeNavigableStrings, + _SomeTags, + ) + +_OneOrMoreStringTypes: TypeAlias = Union[ + Type["NavigableString"], Iterable[Type["NavigableString"]] +] + +_FindMethodName: TypeAlias = Optional[Union["_StrainableElement", "ElementFilter"]] + +# Deprecated module-level attributes. +# See https://peps.python.org/pep-0562/ +_deprecated_names = dict( + whitespace_re="The {name} attribute was deprecated in version 4.7.0. If you need it, make your own copy." +) +#: :meta private: +_deprecated_whitespace_re: Pattern[str] = re.compile(r"\s+") + + +def __getattr__(name: str) -> Any: + if name in _deprecated_names: + message = _deprecated_names[name] + warnings.warn(message.format(name=name), DeprecationWarning, stacklevel=2) + + return globals()[f"_deprecated_{name}"] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +#: Documents output by Beautiful Soup will be encoded with +#: this encoding unless you specify otherwise. +DEFAULT_OUTPUT_ENCODING: str = "utf-8" + +#: A regular expression that can be used to split on whitespace. +nonwhitespace_re: Pattern[str] = re.compile(r"\S+") + +#: These encodings are recognized by Python (so `Tag.encode` +#: could theoretically support them) but XML and HTML don't recognize +#: them (so they should not show up in an XML or HTML document as that +#: document's encoding). +#: +#: If an XML document is encoded in one of these encodings, no encoding +#: will be mentioned in the XML declaration. If an HTML document is +#: encoded in one of these encodings, and the HTML document has a +#: tag that mentions an encoding, the encoding will be given as +#: the empty string. +#: +#: Source: +#: Python documentation, `Python Specific Encodings `_ +PYTHON_SPECIFIC_ENCODINGS: Set[_Encoding] = set( + [ + "idna", + "mbcs", + "oem", + "palmos", + "punycode", + "raw_unicode_escape", + "undefined", + "unicode_escape", + "raw-unicode-escape", + "unicode-escape", + "string-escape", + "string_escape", + ] +) + + +class NamespacedAttribute(str): + """A namespaced attribute (e.g. the 'xml:lang' in 'xml:lang="en"') + which remembers the namespace prefix ('xml') and the name ('lang') + that were used to create it. + """ + + prefix: Optional[str] + name: Optional[str] + namespace: Optional[str] + + def __new__( + cls, + prefix: Optional[str], + name: Optional[str] = None, + namespace: Optional[str] = None, + ) -> Self: + if not name: + # This is the default namespace. Its name "has no value" + # per https://www.w3.org/TR/xml-names/#defaulting + name = None + + if not name: + obj = str.__new__(cls, prefix) + elif not prefix: + # Not really namespaced. + obj = str.__new__(cls, name) + else: + obj = str.__new__(cls, prefix + ":" + name) + obj.prefix = prefix + obj.name = name + obj.namespace = namespace + return obj + + +class AttributeValueWithCharsetSubstitution(str): + """An abstract class standing in for a character encoding specified + inside an HTML ```` tag. + + Subclasses exist for each place such a character encoding might be + found: either inside the ``charset`` attribute + (`CharsetMetaAttributeValue`) or inside the ``content`` attribute + (`ContentMetaAttributeValue`) + + This allows Beautiful Soup to replace that part of the HTML file + with a different encoding when ouputting a tree as a string. + """ + + # The original, un-encoded value of the ``content`` attribute. + #: :meta private: + original_value: str + + def substitute_encoding(self, eventual_encoding: str) -> str: + """Do whatever's necessary in this implementation-specific + portion an HTML document to substitute in a specific encoding. + """ + raise NotImplementedError() + + +class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution): + """A generic stand-in for the value of a ```` tag's ``charset`` + attribute. + + When Beautiful Soup parses the markup ````, the + value of the ``charset`` attribute will become one of these objects. + + If the document is later encoded to an encoding other than UTF-8, its + ```` tag will mention the new encoding instead of ``utf8``. + """ + + def __new__(cls, original_value: str) -> Self: + # We don't need to use the original value for anything, but + # it might be useful for the user to know. + obj = str.__new__(cls, original_value) + obj.original_value = original_value + return obj + + def substitute_encoding(self, eventual_encoding: _Encoding = "utf-8") -> str: + """When an HTML document is being encoded to a given encoding, the + value of a ```` tag's ``charset`` becomes the name of + the encoding. + """ + if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS: + return "" + return eventual_encoding + + +class AttributeValueList(List[str]): + """Class for the list used to hold the values of attributes which + have multiple values (such as HTML's 'class'). It's just a regular + list, but you can subclass it and pass it in to the TreeBuilder + constructor as attribute_value_list_class, to have your subclass + instantiated instead. + """ + + +class AttributeDict(Dict[Any,Any]): + """Superclass for the dictionary used to hold a tag's + attributes. You can use this, but it's just a regular dict with no + special logic. + """ + + +class XMLAttributeDict(AttributeDict): + """A dictionary for holding a Tag's attributes, which processes + incoming values for consistency with the HTML spec. + """ + + def __setitem__(self, key: str, value: Any) -> None: + """Set an attribute value, possibly modifying it to comply with + the XML spec. + + This just means converting common non-string values to + strings: XML attributes may have "any literal string as a + value." + """ + if value is None: + value = "" + if isinstance(value, bool): + # XML does not define any rules for boolean attributes. + # Preserve the old Beautiful Soup behavior (a bool that + # gets converted to a string on output) rather than + # guessing what the value should be. + pass + elif isinstance(value, (int, float)): + # It's dangerous to convert _every_ attribute value into a + # plain string, since an attribute value may be a more + # sophisticated string-like object + # (e.g. CharsetMetaAttributeValue). But we can definitely + # convert numeric values and booleans, which are the most common. + value = str(value) + + super().__setitem__(key, value) + + +class HTMLAttributeDict(AttributeDict): + """A dictionary for holding a Tag's attributes, which processes + incoming values for consistency with the HTML spec, which says + 'Attribute values are a mixture of text and character + references...' + + Basically, this means converting common non-string values into + strings, like XMLAttributeDict, though HTML also has some rules + around boolean attributes that XML doesn't have. + """ + + def __setitem__(self, key: str, value: Any) -> None: + """Set an attribute value, possibly modifying it to comply + with the HTML spec, + """ + if value in (False, None): + # 'The values "true" and "false" are not allowed on + # boolean attributes. To represent a false value, the + # attribute has to be omitted altogether.' + if key in self: + del self[key] + return + if isinstance(value, bool): + # 'If the [boolean] attribute is present, its value must + # either be the empty string or a value that is an ASCII + # case-insensitive match for the attribute's canonical + # name, with no leading or trailing whitespace.' + # + # [fixme] It's not clear to me whether "canonical name" + # means fully-qualified name, unqualified name, or + # (probably not) name with namespace prefix. For now I'm + # going with unqualified name. + if isinstance(key, NamespacedAttribute): + value = key.name + else: + value = key + elif isinstance(value, (int, float)): + # See note in XMLAttributeDict for the reasoning why we + # only do this to numbers. + value = str(value) + super().__setitem__(key, value) + + +class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): + """A generic stand-in for the value of a ```` tag's ``content`` + attribute. + + When Beautiful Soup parses the markup: + ```` + + The value of the ``content`` attribute will become one of these objects. + + If the document is later encoded to an encoding other than UTF-8, its + ```` tag will mention the new encoding instead of ``utf8``. + """ + + #: Match the 'charset' argument inside the 'content' attribute + #: of a tag. + #: :meta private: + CHARSET_RE: Pattern[str] = re.compile(r"((^|;)\s*charset=)([^;]*)", re.M) + + def __new__(cls, original_value: str) -> Self: + cls.CHARSET_RE.search(original_value) + obj = str.__new__(cls, original_value) + obj.original_value = original_value + return obj + + def substitute_encoding(self, eventual_encoding: _Encoding = "utf-8") -> str: + """When an HTML document is being encoded to a given encoding, the + value of the ``charset=`` in a ```` tag's ``content`` becomes + the name of the encoding. + """ + if eventual_encoding in PYTHON_SPECIFIC_ENCODINGS: + return self.CHARSET_RE.sub("", self.original_value) + + def rewrite(match: re.Match[str]) -> str: + return match.group(1) + eventual_encoding + + return self.CHARSET_RE.sub(rewrite, self.original_value) + + +class PageElement(object): + """An abstract class representing a single element in the parse tree. + + `NavigableString`, `Tag`, etc. are all subclasses of + `PageElement`. For this reason you'll see a lot of methods that + return `PageElement`, but you'll never see an actual `PageElement` + object. For the most part you can think of `PageElement` as + meaning "a `Tag` or a `NavigableString`." + """ + + #: In general, we can't tell just by looking at an element whether + #: it's contained in an XML document or an HTML document. But for + #: `Tag` objects (q.v.) we can store this information at parse time. + #: :meta private: + known_xml: Optional[bool] = None + + #: Whether or not this element has been decomposed from the tree + #: it was created in. + _decomposed: bool + + parent: Optional[Tag] + next_element: _AtMostOneElement + previous_element: _AtMostOneElement + next_sibling: _AtMostOneElement + previous_sibling: _AtMostOneElement + + #: Whether or not this element is hidden from generated output. + #: Only the `BeautifulSoup` object itself is hidden. + hidden: bool = False + + def setup( + self, + parent: Optional[Tag] = None, + previous_element: _AtMostOneElement = None, + next_element: _AtMostOneElement = None, + previous_sibling: _AtMostOneElement = None, + next_sibling: _AtMostOneElement = None, + ) -> None: + """Sets up the initial relations between this element and + other elements. + + :param parent: The parent of this element. + + :param previous_element: The element parsed immediately before + this one. + + :param next_element: The element parsed immediately after + this one. + + :param previous_sibling: The most recently encountered element + on the same level of the parse tree as this one. + + :param previous_sibling: The next element to be encountered + on the same level of the parse tree as this one. + """ + self.parent = parent + + self.previous_element = previous_element + if self.previous_element is not None: + self.previous_element.next_element = self + + self.next_element = next_element + if self.next_element is not None: + self.next_element.previous_element = self + + self.next_sibling = next_sibling + if self.next_sibling is not None: + self.next_sibling.previous_sibling = self + + if ( + previous_sibling is None + and self.parent is not None + and self.parent.contents + ): + previous_sibling = self.parent.contents[-1] + + self.previous_sibling = previous_sibling + if self.previous_sibling is not None: + self.previous_sibling.next_sibling = self + + def format_string(self, s: str, formatter: Optional[_FormatterOrName]) -> str: + """Format the given string using the given formatter. + + :param s: A string. + :param formatter: A Formatter object, or a string naming one of the standard formatters. + """ + if formatter is None: + return s + if not isinstance(formatter, Formatter): + formatter = self.formatter_for_name(formatter) + output = formatter.substitute(s) + return output + + def formatter_for_name( + self, formatter_name: Union[_FormatterOrName, _EntitySubstitutionFunction] + ) -> Formatter: + """Look up or create a Formatter for the given identifier, + if necessary. + + :param formatter: Can be a `Formatter` object (used as-is), a + function (used as the entity substitution hook for an + `bs4.formatter.XMLFormatter` or + `bs4.formatter.HTMLFormatter`), or a string (used to look + up an `bs4.formatter.XMLFormatter` or + `bs4.formatter.HTMLFormatter` in the appropriate registry. + + """ + if isinstance(formatter_name, Formatter): + return formatter_name + c: type[Formatter] + registry: Mapping[Optional[str], Formatter] + if self._is_xml: + c = XMLFormatter + registry = XMLFormatter.REGISTRY + else: + c = HTMLFormatter + registry = HTMLFormatter.REGISTRY + if callable(formatter_name): + return c(entity_substitution=formatter_name) + return registry[formatter_name] + + @property + def _is_xml(self) -> bool: + """Is this element part of an XML tree or an HTML tree? + + This is used in formatter_for_name, when deciding whether an + XMLFormatter or HTMLFormatter is more appropriate. It can be + inefficient, but it should be called very rarely. + """ + if self.known_xml is not None: + # Most of the time we will have determined this when the + # document is parsed. + return self.known_xml + + # Otherwise, it's likely that this element was created by + # direct invocation of the constructor from within the user's + # Python code. + if self.parent is None: + # This is the top-level object. It should have .known_xml set + # from tree creation. If not, take a guess--BS is usually + # used on HTML markup. + return getattr(self, "is_xml", False) + return self.parent._is_xml + + nextSibling = _deprecated_alias("nextSibling", "next_sibling", "4.0.0") + previousSibling = _deprecated_alias("previousSibling", "previous_sibling", "4.0.0") + + def __deepcopy__(self, memo: Dict[Any, Any], recursive: bool = False) -> Self: + raise NotImplementedError() + + def __copy__(self) -> Self: + """A copy of a PageElement can only be a deep copy, because + only one PageElement can occupy a given place in a parse tree. + """ + return self.__deepcopy__({}) + + default: Iterable[type[NavigableString]] = tuple() #: :meta private: + + def _all_strings( + self, strip: bool = False, types: Iterable[type[NavigableString]] = default + ) -> Iterator[str]: + """Yield all strings of certain classes, possibly stripping them. + + This is implemented differently in `Tag` and `NavigableString`. + """ + raise NotImplementedError() + + @property + def stripped_strings(self) -> Iterator[str]: + """Yield all interesting strings in this PageElement, stripping them + first. + + See `Tag` for information on which strings are considered + interesting in a given context. + """ + for string in self._all_strings(True): + yield string + + def get_text( + self, + separator: str = "", + strip: bool = False, + types: Iterable[Type[NavigableString]] = default, + ) -> str: + """Get all child strings of this PageElement, concatenated using the + given separator. + + :param separator: Strings will be concatenated using this separator. + + :param strip: If True, strings will be stripped before being + concatenated. + + :param types: A tuple of NavigableString subclasses. Any + strings of a subclass not found in this list will be + ignored. Although there are exceptions, the default + behavior in most cases is to consider only NavigableString + and CData objects. That means no comments, processing + instructions, etc. + + :return: A string. + """ + return separator.join([s for s in self._all_strings(strip, types=types)]) + + getText = get_text + text = property(get_text) + + def replace_with(self, *args: _InsertableElement) -> Self: + """Replace this `PageElement` with one or more other elements, + objects, keeping the rest of the tree the same. + + :return: This `PageElement`, no longer part of the tree. + """ + if self.parent is None: + raise ValueError( + "Cannot replace one element with another when the " + "element to be replaced is not part of a tree." + ) + if len(args) == 1 and args[0] is self: + # Replacing an element with itself is a no-op. + return self + if any(x is self.parent for x in args): + raise ValueError("Cannot replace a Tag with its parent.") + old_parent = self.parent + my_index = self.parent.index(self) + self.extract(_self_index=my_index) + for idx, replace_with in enumerate(args, start=my_index): + old_parent.insert(idx, replace_with) + return self + + replaceWith = _deprecated_function_alias("replaceWith", "replace_with", "4.0.0") + + def wrap(self, wrap_inside: Tag) -> Tag: + """Wrap this `PageElement` inside a `Tag`. + + :return: ``wrap_inside``, occupying the position in the tree that used + to be occupied by this object, and with this object now inside it. + """ + me = self.replace_with(wrap_inside) + wrap_inside.append(me) + return wrap_inside + + def extract(self, _self_index: Optional[int] = None) -> Self: + """Destructively rips this element out of the tree. + + :param _self_index: The location of this element in its parent's + .contents, if known. Passing this in allows for a performance + optimization. + + :return: this `PageElement`, no longer part of the tree. + """ + if self.parent is not None: + if _self_index is None: + _self_index = self.parent.index(self) + del self.parent.contents[_self_index] + + # Find the two elements that would be next to each other if + # this element (and any children) hadn't been parsed. Connect + # the two. + last_child = self._last_descendant() + + # last_child can't be None because we passed accept_self=True + # into _last_descendant. Worst case, last_child will be + # self. Making this cast removes several mypy complaints later + # on as we manipulate last_child. + last_child = cast(PageElement, last_child) + next_element = last_child.next_element + + if self.previous_element is not None: + if self.previous_element is not next_element: + self.previous_element.next_element = next_element + if next_element is not None and next_element is not self.previous_element: + next_element.previous_element = self.previous_element + self.previous_element = None + last_child.next_element = None + + self.parent = None + if ( + self.previous_sibling is not None + and self.previous_sibling is not self.next_sibling + ): + self.previous_sibling.next_sibling = self.next_sibling + if ( + self.next_sibling is not None + and self.next_sibling is not self.previous_sibling + ): + self.next_sibling.previous_sibling = self.previous_sibling + self.previous_sibling = self.next_sibling = None + return self + + def decompose(self) -> None: + """Recursively destroys this `PageElement` and its children. + + The element will be removed from the tree and wiped out; so + will everything beneath it. + + The behavior of a decomposed `PageElement` is undefined and you + should never use one for anything, but if you need to *check* + whether an element has been decomposed, you can use the + `PageElement.decomposed` property. + """ + self.extract() + e: _AtMostOneElement = self + next_up: _AtMostOneElement = None + while e is not None: + next_up = e.next_element + e.__dict__.clear() + if isinstance(e, Tag): + e.name = "" + e.contents = [] + e._decomposed = True + e = next_up + + def _last_descendant( + self, is_initialized: bool = True, accept_self: bool = True + ) -> _AtMostOneElement: + """Finds the last element beneath this object to be parsed. + + Special note to help you figure things out if your type + checking is tripped up by the fact that this method returns + _AtMostOneElement instead of PageElement: the only time + this method returns None is if `accept_self` is False and the + `PageElement` has no children--either it's a NavigableString + or an empty Tag. + + :param is_initialized: Has `PageElement.setup` been called on + this `PageElement` yet? + + :param accept_self: Is ``self`` an acceptable answer to the + question? + """ + if is_initialized and self.next_sibling is not None: + last_child = self.next_sibling.previous_element + else: + last_child = self + while isinstance(last_child, Tag) and last_child.contents: + last_child = last_child.contents[-1] + if not accept_self and last_child is self: + last_child = None + return last_child + + _lastRecursiveChild = _deprecated_alias( + "_lastRecursiveChild", "_last_descendant", "4.0.0" + ) + + def insert_before(self, *args: _InsertableElement) -> List[PageElement]: + """Makes the given element(s) the immediate predecessor of this one. + + All the elements will have the same `PageElement.parent` as + this one, and the given elements will occur immediately before + this one. + + :param args: One or more PageElements. + + :return The list of PageElements that were inserted. + """ + parent = self.parent + if parent is None: + raise ValueError("Element has no parent, so 'before' has no meaning.") + if any(x is self for x in args): + raise ValueError("Can't insert an element before itself.") + results: List[PageElement] = [] + for predecessor in args: + # Extract first so that the index won't be screwed up if they + # are siblings. + if isinstance(predecessor, PageElement): + predecessor.extract() + index = parent.index(self) + results.extend(parent.insert(index, predecessor)) + + return results + + def insert_after(self, *args: _InsertableElement) -> List[PageElement]: + """Makes the given element(s) the immediate successor of this one. + + The elements will have the same `PageElement.parent` as this + one, and the given elements will occur immediately after this + one. + + :param args: One or more PageElements. + + :return The list of PageElements that were inserted. + """ + # Do all error checking before modifying the tree. + parent = self.parent + if parent is None: + raise ValueError("Element has no parent, so 'after' has no meaning.") + if any(x is self for x in args): + raise ValueError("Can't insert an element after itself.") + + offset = 0 + results: List[PageElement] = [] + for successor in args: + # Extract first so that the index won't be screwed up if they + # are siblings. + if isinstance(successor, PageElement): + successor.extract() + index = parent.index(self) + results.extend(parent.insert(index + 1 + offset, successor)) + offset += 1 + + return results + + # For the suppression of this pyright warning, see discussion here: + # https://github.com/microsoft/pyright/issues/10929 + @overload + def find_next( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None=None, + **kwargs: _StrainableAttribute, + ) -> _AtMostOneTag: + ... + + @overload + def find_next( + self, + name: None=None, + attrs: None=None, + string: _StrainableString="", + **kwargs: _StrainableAttribute, + ) -> _AtMostOneNavigableString: + ... + + def find_next( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + **kwargs: _StrainableAttribute, + ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]: + """Find the first PageElement that matches the given criteria and + appears later in the document than this PageElement. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a NavigableString with specific text. + :kwargs: Additional filters on attribute values. + """ + return self._find_one(self.find_all_next, name, attrs, string, **kwargs) + + findNext = _deprecated_function_alias("findNext", "find_next", "4.0.0") + + @overload + def find_all_next( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeTags: + ... + + @overload + def find_all_next( + self, + name: None = None, + attrs: None = None, + string: _StrainableString = "", + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeNavigableStrings: + ... + + def find_all_next( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]: + """Find all `PageElement` objects that match the given criteria and + appear later in the document than this `PageElement`. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a NavigableString with specific text. + :param limit: Stop looking after finding this many results. + :param _stacklevel: Used internally to improve warning messages. + :kwargs: Additional filters on attribute values. + """ + return self._find_all( + name, + attrs, + string, + limit, + self.next_elements, + _stacklevel=_stacklevel + 1, + **kwargs, + ) + + findAllNext = _deprecated_function_alias("findAllNext", "find_all_next", "4.0.0") + + @overload + def find_next_sibling( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None=None, + **kwargs: _StrainableAttribute, + ) -> _AtMostOneTag: + ... + + @overload + def find_next_sibling( + self, + name: None=None, + attrs: None=None, + string: _StrainableString="", + **kwargs: _StrainableAttribute, + ) -> _AtMostOneNavigableString: + ... + + def find_next_sibling( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + **kwargs: _StrainableAttribute, + ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]: + """Find the closest sibling to this PageElement that matches the + given criteria and appears later in the document. + + All find_* methods take a common set of arguments. See the + online documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a `NavigableString` with specific text. + :kwargs: Additional filters on attribute values. + """ + return self._find_one(self.find_next_siblings, name, attrs, string, **kwargs) + + findNextSibling = _deprecated_function_alias( + "findNextSibling", "find_next_sibling", "4.0.0" + ) + + @overload + def find_next_siblings( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeTags: + ... + + @overload + def find_next_siblings( + self, + name: None = None, + attrs: None = None, + string: _StrainableString = "", + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeNavigableStrings: + ... + + def find_next_siblings( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]: + """Find all siblings of this `PageElement` that match the given criteria + and appear later in the document. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a `NavigableString` with specific text. + :param limit: Stop looking after finding this many results. + :param _stacklevel: Used internally to improve warning messages. + :kwargs: Additional filters on attribute values. + """ + return self._find_all( + name, + attrs, + string, + limit, + self.next_siblings, + _stacklevel=_stacklevel + 1, + **kwargs, + ) + + findNextSiblings = _deprecated_function_alias( + "findNextSiblings", "find_next_siblings", "4.0.0" + ) + fetchNextSiblings = _deprecated_function_alias( + "fetchNextSiblings", "find_next_siblings", "3.0.0" + ) + + @overload + def find_previous( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None=None, + **kwargs: _StrainableAttribute, + ) -> _AtMostOneTag: + ... + + @overload + def find_previous( + self, + name: None=None, + attrs: None=None, + string: _StrainableString="", + **kwargs: _StrainableAttribute, + ) -> _AtMostOneNavigableString: + ... + + def find_previous( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + **kwargs: _StrainableAttribute, + ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]: + """Look backwards in the document from this `PageElement` and find the + first `PageElement` that matches the given criteria. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a `NavigableString` with specific text. + :kwargs: Additional filters on attribute values. + """ + return self._find_one(self.find_all_previous, name, attrs, string, **kwargs) + + findPrevious = _deprecated_function_alias("findPrevious", "find_previous", "3.0.0") + + @overload + def find_all_previous( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeTags: + ... + + @overload + def find_all_previous( + self, + name: None = None, + attrs: None = None, + string: _StrainableString = "", + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeNavigableStrings: + ... + + def find_all_previous( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]: + """Look backwards in the document from this `PageElement` and find all + `PageElement` that match the given criteria. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a `NavigableString` with specific text. + :param limit: Stop looking after finding this many results. + :param _stacklevel: Used internally to improve warning messages. + :kwargs: Additional filters on attribute values. + """ + return self._find_all( + name, + attrs, + string, + limit, + self.previous_elements, + _stacklevel=_stacklevel + 1, + **kwargs, + ) + + findAllPrevious = _deprecated_function_alias( + "findAllPrevious", "find_all_previous", "4.0.0" + ) + fetchAllPrevious = _deprecated_function_alias( + "fetchAllPrevious", "find_all_previous", "3.0.0" + ) + + @overload + def find_previous_sibling( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None=None, + **kwargs: _StrainableAttribute, + ) -> _AtMostOneTag: + ... + + @overload + def find_previous_sibling( + self, + name: None=None, + attrs: None=None, + string: _StrainableString="", + **kwargs: _StrainableAttribute, + ) -> _AtMostOneNavigableString: + ... + + def find_previous_sibling( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + **kwargs: _StrainableAttribute, + ) -> Union[_AtMostOneTag,_AtMostOneNavigableString,_AtMostOneElement]: + """Returns the closest sibling to this `PageElement` that matches the + given criteria and appears earlier in the document. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a `NavigableString` with specific text. + :kwargs: Additional filters on attribute values. + """ + return self._find_one( + self.find_previous_siblings, name, attrs, string, **kwargs + ) + + findPreviousSibling = _deprecated_function_alias( + "findPreviousSibling", "find_previous_sibling", "4.0.0" + ) + + @overload + def find_previous_siblings( # pyright: ignore [reportOverlappingOverload] + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: None = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeTags: + ... + + @overload + def find_previous_siblings( + self, + name: None = None, + attrs: None = None, + string: _StrainableString = "", + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeNavigableStrings: + ... + + def find_previous_siblings( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + string: Optional[_StrainableString] = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> Union[_SomeTags,_SomeNavigableStrings,_QueryResults]: + """Returns all siblings to this PageElement that match the + given criteria and appear earlier in the document. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param string: A filter for a NavigableString with specific text. + :param limit: Stop looking after finding this many results. + :param _stacklevel: Used internally to improve warning messages. + :kwargs: Additional filters on attribute values. + """ + return self._find_all( + name, + attrs, + string, + limit, + self.previous_siblings, + _stacklevel=_stacklevel + 1, + **kwargs, + ) + + findPreviousSiblings = _deprecated_function_alias( + "findPreviousSiblings", "find_previous_siblings", "4.0.0" + ) + fetchPreviousSiblings = _deprecated_function_alias( + "fetchPreviousSiblings", "find_previous_siblings", "3.0.0" + ) + + def find_parent( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + **kwargs: _StrainableAttribute, + ) -> _AtMostOneTag: + """Find the closest parent of this PageElement that matches the given + criteria. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param self: Whether the PageElement itself should be considered + as one of its 'parents'. + :kwargs: Additional filters on attribute values. + """ + # NOTE: We can't use _find_one because findParents takes a different + # set of arguments. + r = None + results = self.find_parents( + name, attrs, 1, _stacklevel=3, **kwargs + ) + if results: + r = results[0] + return r + + findParent = _deprecated_function_alias("findParent", "find_parent", "4.0.0") + + def find_parents( + self, + name: _FindMethodName = None, + attrs: Optional[_StrainableAttributes] = None, + limit: Optional[int] = None, + _stacklevel: int = 2, + **kwargs: _StrainableAttribute, + ) -> _SomeTags: + """Find all parents of this `PageElement` that match the given criteria. + + All find_* methods take a common set of arguments. See the online + documentation for detailed explanations. + + :param name: A filter on tag name. + :param attrs: Additional filters on attribute values. + :param limit: Stop looking after finding this many results. + :param _stacklevel: Used internally to improve warning messages. + :kwargs: Additional filters on attribute values. + """ + iterator = self.parents + # Only Tags can have children, so this ResultSet will contain + # nothing but Tags. + return cast(ResultSet[Tag], self._find_all( + name, attrs, None, limit, iterator, _stacklevel=_stacklevel + 1, **kwargs + )) + + findParents = _deprecated_function_alias("findParents", "find_parents", "4.0.0") + fetchParents = _deprecated_function_alias("fetchParents", "find_parents", "3.0.0") + + @property + def next(self) -> _AtMostOneElement: + """The `PageElement`, if any, that was parsed just after this one.""" + return self.next_element + + @property + def previous(self) -> _AtMostOneElement: + """The `PageElement`, if any, that was parsed just before this one.""" + return self.previous_element + + # These methods do the real heavy lifting. + + def _find_one( + self, + # TODO-TYPING: "There is no syntax to indicate optional or + # keyword arguments; such function types are rarely used + # as callback types." - So, not sure how to get more + # specific here. + method: Callable, + name: _FindMethodName, + attrs: Optional[_StrainableAttributes], + string: Optional[_StrainableString], + **kwargs: _StrainableAttribute, + ) -> _AtMostOneElement: + r: _AtMostOneElement = None + results: _QueryResults = method(name, attrs, string, 1, _stacklevel=4, **kwargs) + if results: + r = results[0] + return r + + def _find_all( + self, + name: _FindMethodName, + attrs: Optional[_StrainableAttributes], + string: Optional[_StrainableString], + limit: Optional[int], + generator: Iterator[PageElement], + _stacklevel: int = 3, + **kwargs: _StrainableAttribute, + ) -> _QueryResults: + """Iterates over a generator looking for things that match.""" + + if string is None and "text" in kwargs: + string = kwargs.pop("text") + warnings.warn( + "The 'text' argument to find()-type methods is deprecated. Use 'string' instead.", + DeprecationWarning, + stacklevel=_stacklevel, + ) + + if "_class" in kwargs: + warnings.warn( + AttributeResemblesVariableWarning.MESSAGE + % dict( + original="_class", + autocorrect="class_", + ), + AttributeResemblesVariableWarning, + stacklevel=_stacklevel, + ) + + from bs4.filter import ElementFilter + + if isinstance(name, ElementFilter): + matcher = name + else: + matcher = SoupStrainer(name, attrs, string, **kwargs) + + result: MutableSequence[_OneElement] + if string is None and not limit and not attrs and not kwargs: + if name is True or name is None: + # Optimization to find all tags. + result = [element for element in generator if isinstance(element, Tag)] + return ResultSet(matcher, result) + elif isinstance(name, str): + # Optimization to find all tags with a given name. + if name.count(":") == 1: + # This is a name with a prefix. If this is a namespace-aware document, + # we need to match the local name against tag.name. If not, + # we need to match the fully-qualified name against tag.name. + prefix, local_name = name.split(":", 1) + else: + prefix = None + local_name = name + result = [] + for element in generator: + if not isinstance(element, Tag): + continue + if element.name == name or ( + element.name == local_name + and (prefix is None or element.prefix == prefix) + ): + result.append(element) + return ResultSet(matcher, result) + return matcher.find_all(generator, limit) + + # These generators can be used to navigate starting from both + # NavigableStrings and Tags. + @property + def next_elements(self) -> Iterator[PageElement]: + """All PageElements that were parsed after this one.""" + i = self.next_element + while i is not None: + successor = i.next_element + yield i + i = successor + + @property + def self_and_next_elements(self) -> Iterator[PageElement]: + """This PageElement, then all PageElements that were parsed after it.""" + return self._self_and(self.next_elements) + + @property + def next_siblings(self) -> Iterator[PageElement]: + """All PageElements that are siblings of this one but were parsed + later. + """ + i = self.next_sibling + while i is not None: + successor = i.next_sibling + yield i + i = successor + + @property + def self_and_next_siblings(self) -> Iterator[PageElement]: + """This PageElement, then all of its siblings.""" + return self._self_and(self.next_siblings) + + @property + def previous_elements(self) -> Iterator[PageElement]: + """All PageElements that were parsed before this one. + + :yield: A sequence of PageElements. + """ + i = self.previous_element + while i is not None: + successor = i.previous_element + yield i + i = successor + + @property + def self_and_previous_elements(self) -> Iterator[PageElement]: + """This PageElement, then all elements that were parsed + earlier.""" + return self._self_and(self.previous_elements) + + @property + def previous_siblings(self) -> Iterator[PageElement]: + """All PageElements that are siblings of this one but were parsed + earlier. + + :yield: A sequence of PageElements. + """ + i = self.previous_sibling + while i is not None: + successor = i.previous_sibling + yield i + i = successor + + @property + def self_and_previous_siblings(self) -> Iterator[PageElement]: + """This PageElement, then all of its siblings that were parsed + earlier.""" + return self._self_and(self.previous_siblings) + + @property + def parents(self) -> Iterator[Tag]: + """All elements that are parents of this PageElement. + + :yield: A sequence of Tags, ending with a BeautifulSoup object. + """ + i = self.parent + while i is not None: + successor = i.parent + yield i + i = successor + + @property + def self_and_parents(self) -> Iterator[PageElement]: + """This element, then all of its parents. + + :yield: A sequence of PageElements, ending with a BeautifulSoup object. + """ + return self._self_and(self.parents) + + def _self_and(self, other_generator:Iterator[PageElement]) -> Iterator[PageElement]: + """Modify a generator by yielding this element, then everything + yielded by the other generator. + """ + if not self.hidden: + yield self + for i in other_generator: + yield i + + @property + def decomposed(self) -> bool: + """Check whether a PageElement has been decomposed.""" + return getattr(self, "_decomposed", False) or False + + @_deprecated("next_elements", "4.0.0") + def nextGenerator(self) -> Iterator[PageElement]: + ":meta private:" + return self.next_elements + + @_deprecated("next_siblings", "4.0.0") + def nextSiblingGenerator(self) -> Iterator[PageElement]: + ":meta private:" + return self.next_siblings + + @_deprecated("previous_elements", "4.0.0") + def previousGenerator(self) -> Iterator[PageElement]: + ":meta private:" + return self.previous_elements + + @_deprecated("previous_siblings", "4.0.0") + def previousSiblingGenerator(self) -> Iterator[PageElement]: + ":meta private:" + return self.previous_siblings + + @_deprecated("parents", "4.0.0") + def parentGenerator(self) -> Iterator[PageElement]: + ":meta private:" + return self.parents + + +class NavigableString(str, PageElement): + """A Python string that is part of a parse tree. + + When Beautiful Soup parses the markup ``penguin``, it will + create a `NavigableString` for the string "penguin". + """ + + #: A string prepended to the body of the 'real' string + #: when formatting it as part of a document, such as the '' + #: in an HTML comment. + SUFFIX: str = "" + + def __new__(cls, value: Union[str, bytes]) -> Self: + """Create a new NavigableString. + + When unpickling a NavigableString, this method is called with + the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be + passed in to the superclass's __new__ or the superclass won't know + how to handle non-ASCII characters. + """ + if isinstance(value, str): + u = str.__new__(cls, value) + else: + u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) + u.hidden = False + u.setup() + return u + + def __deepcopy__(self, memo: Dict[Any, Any], recursive: bool = False) -> Self: + """A copy of a NavigableString has the same contents and class + as the original, but it is not connected to the parse tree. + + :param recursive: This parameter is ignored; it's only defined + so that NavigableString.__deepcopy__ implements the same + signature as Tag.__deepcopy__. + """ + return type(self)(self) + + def __getnewargs__(self) -> Tuple[str]: + return (str(self),) + + # TODO-TYPING This should be SupportsIndex|slice but SupportsIndex + # is introduced in 3.8. This can be changed once 3.7 support is dropped. + def __getitem__(self, key: Union[int|slice]) -> str: # type:ignore + """Raise an exception """ + if isinstance(key, str): + raise TypeError("string indices must be integers, not '{0}'. Are you treating a NavigableString like a Tag?".format(key.__class__.__name__)) + return super(NavigableString, self).__getitem__(key) + + @property + def string(self) -> str: + """Convenience property defined to match `Tag.string`. + + :return: This property always returns the `NavigableString` it was + called on. + + :meta private: + """ + return self + + def output_ready(self, formatter: _FormatterOrName = "minimal") -> str: + """Run the string through the provided formatter, making it + ready for output as part of an HTML or XML document. + + :param formatter: A `Formatter` object, or a string naming one + of the standard formatters. + """ + output = self.format_string(self, formatter) + return self.PREFIX + output + self.SUFFIX + + @property + def name(self) -> None: + """Since a NavigableString is not a Tag, it has no .name. + + This property is implemented so that code like this doesn't crash + when run on a mixture of Tag and NavigableString objects: + [x.name for x in tag.children] + + :meta private: + """ + return None + + @name.setter + def name(self, name: str) -> None: + """Prevent NavigableString.name from ever being set. + + :meta private: + """ + raise AttributeError("A NavigableString cannot be given a name.") + + def _all_strings( + self, strip: bool = False, types: _OneOrMoreStringTypes = PageElement.default + ) -> Iterator[str]: + """Yield all strings of certain classes, possibly stripping them. + + This makes it easy for NavigableString to implement methods + like get_text() as conveniences, creating a consistent + text-extraction API across all PageElements. + + :param strip: If True, all strings will be stripped before being + yielded. + + :param types: A tuple of NavigableString subclasses. If this + NavigableString isn't one of those subclasses, the + sequence will be empty. By default, the subclasses + considered are NavigableString and CData objects. That + means no comments, processing instructions, etc. + + :yield: A sequence that either contains this string, or is empty. + """ + if types is self.default: + # This is kept in Tag because it's full of subclasses of + # this class, which aren't defined until later in the file. + types = Tag.MAIN_CONTENT_STRING_TYPES + + # Do nothing if the caller is looking for specific types of + # string, and we're of a different type. + # + # We check specific types instead of using isinstance(self, + # types) because all of these classes subclass + # NavigableString. Anyone who's using this feature probably + # wants generic NavigableStrings but not other stuff. + my_type = type(self) + if types is not None: + if isinstance(types, type): + # Looking for a single type. + if my_type is not types: + return + elif my_type not in types: + # Looking for one of a list of types. + return + + value = self + if strip: + final_value = value.strip() + else: + final_value = self + if len(final_value) > 0: + yield final_value + + @property + def strings(self) -> Iterator[str]: + """Yield this string, but only if it is interesting. + + This is defined the way it is for compatibility with + `Tag.strings`. See `Tag` for information on which strings are + interesting in a given context. + + :yield: A sequence that either contains this string, or is empty. + """ + return self._all_strings() + + +class PreformattedString(NavigableString): + """A `NavigableString` not subject to the normal formatting rules. + + This is an abstract class used for special kinds of strings such + as comments (`Comment`) and CDATA blocks (`CData`). + """ + + PREFIX: str = "" + SUFFIX: str = "" + + def output_ready(self, formatter: Optional[_FormatterOrName] = None) -> str: + """Make this string ready for output by adding any subclass-specific + prefix or suffix. + + :param formatter: A `Formatter` object, or a string naming one + of the standard formatters. The string will be passed into the + `Formatter`, but only to trigger any side effects: the return + value is ignored. + + :return: The string, with any subclass-specific prefix and + suffix added on. + """ + if formatter is not None: + self.format_string(self, formatter) + return self.PREFIX + self + self.SUFFIX + + +class CData(PreformattedString): + """A `CDATA section `_.""" + + PREFIX: str = "" + + +class ProcessingInstruction(PreformattedString): + """A SGML processing instruction.""" + + PREFIX: str = "" + + +class XMLProcessingInstruction(ProcessingInstruction): + """An `XML processing instruction `_.""" + + PREFIX: str = "" + + +class Comment(PreformattedString): + """An `HTML comment `_ or `XML comment `_.""" + + PREFIX: str = "" + + +class Declaration(PreformattedString): + """An `XML declaration `_.""" + + PREFIX: str = "" + + +class Doctype(PreformattedString): + """A `document type declaration `_.""" + + @classmethod + def for_name_and_ids( + cls, name: str, pub_id: Optional[str], system_id: Optional[str] + ) -> Doctype: + """Generate an appropriate document type declaration for a given + public ID and system ID. + + :param name: The name of the document's root element, e.g. 'html'. + :param pub_id: The Formal Public Identifier for this document type, + e.g. '-//W3C//DTD XHTML 1.1//EN' + :param system_id: The system identifier for this document type, + e.g. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' + """ + return Doctype(cls._string_for_name_and_ids(name, pub_id, system_id)) + + @classmethod + def _string_for_name_and_ids( + cls, name: str, pub_id: Optional[str], system_id: Optional[str] + ) -> str: + """Generate a string to be used as the basis of a Doctype object. + + This is a separate method from for_name_and_ids() because the lxml + TreeBuilder needs to call it. + """ + value = name or "" + if pub_id is not None: + value += ' PUBLIC "%s"' % pub_id + if system_id is not None: + value += ' "%s"' % system_id + elif system_id is not None: + value += ' SYSTEM "%s"' % system_id + return value + + PREFIX: str = "\n" + + +class Stylesheet(NavigableString): + """A `NavigableString` representing the contents of a `