conda.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2020, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. # language=rst
  12. """
  13. Additional helper methods for working specifically with Anaconda distributions are found at
  14. :mod:`PyInstaller.utils.hooks.conda_support<PyInstaller.utils.hooks.conda>`
  15. which is designed to mimic (albeit loosely) the `importlib.metadata`_ package. These functions find and parse the
  16. distribution metadata from json files located in the ``conda-meta`` directory.
  17. .. versionadded:: 4.2.0
  18. This module is available only if run inside a Conda environment. Usage of this module should therefore be wrapped in
  19. a conditional clause::
  20. from PyInstaller.utils.hooks import is_pure_conda
  21. if is_pure_conda:
  22. from PyInstaller.utils.hooks import conda_support
  23. # Code goes here. e.g.
  24. binaries = conda_support.collect_dynamic_libs("numpy")
  25. ...
  26. Packages are all referenced by the *distribution name* you use to install it, rather than the *package name* you import
  27. it with. I.e., use ``distribution("pillow")`` instead of ``distribution("PIL")`` or use ``package_distribution("PIL")``.
  28. """
  29. import fnmatch
  30. import json
  31. import sys
  32. from pathlib import Path
  33. from typing import Iterable, List
  34. from PyInstaller import compat
  35. from PyInstaller.log import logger
  36. if compat.is_py38:
  37. from importlib.metadata import PackagePath as _PackagePath
  38. else:
  39. from importlib_metadata import PackagePath as _PackagePath
  40. # Conda virtual environments each get their own copy of `conda-meta` so the use of `sys.prefix` instead of
  41. # `sys.base_prefix`, `sys.real_prefix` or anything from our `compat` module is intentional.
  42. CONDA_ROOT = Path(sys.prefix)
  43. CONDA_META_DIR = CONDA_ROOT / "conda-meta"
  44. # Find all paths in `sys.path` that are inside Conda root.
  45. PYTHONPATH_PREFIXES = []
  46. for _path in sys.path:
  47. _path = Path(_path)
  48. try:
  49. PYTHONPATH_PREFIXES.append(_path.relative_to(sys.prefix))
  50. except ValueError:
  51. pass
  52. PYTHONPATH_PREFIXES.sort(key=lambda p: len(p.parts), reverse=True)
  53. class Distribution(object):
  54. """
  55. A bucket class representation of a Conda distribution.
  56. This bucket exports the following attributes:
  57. :ivar name: The distribution's name.
  58. :ivar version: Its version.
  59. :ivar files: All filenames as :meth:`PackagePath`\\ s included with this distribution.
  60. :ivar dependencies: Names of other distributions that this distribution depends on (with version constraints
  61. removed).
  62. :ivar packages: Names of importable packages included in this distribution.
  63. This class is not intended to be constructed directly by users. Rather use :meth:`distribution` or
  64. :meth:`package_distribution` to provide one for you.
  65. """
  66. def __init__(self, json_path):
  67. try:
  68. self._json_path = Path(json_path)
  69. assert self._json_path.exists()
  70. except (TypeError, AssertionError):
  71. raise TypeError(
  72. "Distribution requires a path to a conda-meta json. Perhaps you want "
  73. "`distribution({})` instead?".format(repr(json_path))
  74. )
  75. # Everything we need (including this distribution's name) is kept in the metadata json.
  76. self.raw = json.loads(self._json_path.read_text())
  77. # Unpack the more useful contents of the json.
  78. self.name = self.raw["name"]
  79. self.version = self.raw["version"]
  80. self.files = [PackagePath(i) for i in self.raw["files"]]
  81. self.dependencies = self._init_dependencies()
  82. self.packages = self._init_package_names()
  83. def __repr__(self):
  84. return "{}(name=\"{}\", packages={})".format(type(self).__name__, self.name, self.packages)
  85. def _init_dependencies(self):
  86. """
  87. Read dependencies from ``self.raw["depends"]``.
  88. :return: Dependent distribution names.
  89. :rtype: list
  90. The names in ``self.raw["depends"]`` come with extra version constraint information which must be stripped.
  91. """
  92. dependencies = []
  93. # For each dependency:
  94. for dependency in self.raw["depends"]:
  95. # ``dependency`` is a string of the form: "[name] [version constraints]"
  96. name, *version_constraints = dependency.split(maxsplit=1)
  97. dependencies.append(name)
  98. return dependencies
  99. def _init_package_names(self):
  100. """
  101. Search ``self.files`` for package names shipped by this distribution.
  102. :return: Package names.
  103. :rtype: list
  104. These are names you would ``import`` rather than names you would install.
  105. """
  106. packages = []
  107. for file in self.files:
  108. package = _get_package_name(file)
  109. if package is not None:
  110. packages.append(package)
  111. return packages
  112. @classmethod
  113. def from_name(cls, name):
  114. """
  115. Get distribution information for a given distribution **name** (i.e., something you would ``conda install``).
  116. :rtype: :class:`Distribution`
  117. """
  118. if name in distributions:
  119. return distributions[name]
  120. raise ModuleNotFoundError(
  121. "Distribution {} is either not installed or was not installed using Conda.".format(name)
  122. )
  123. @classmethod
  124. def from_package_name(cls, name):
  125. """
  126. Get distribution information for a **package** (i.e., something you would import).
  127. :rtype: :class:`Distribution`
  128. For example, the package ``pkg_resources`` belongs to the distribution ``setuptools``, which contains three
  129. packages.
  130. >>> package_distribution("pkg_resources")
  131. Distribution(name="setuptools",
  132. packages=['easy_install', 'pkg_resources', 'setuptools'])
  133. """
  134. if name in distributions_by_package:
  135. return distributions_by_package[name]
  136. raise ModuleNotFoundError("Package {} is either not installed or was not installed using Conda.".format(name))
  137. distribution = Distribution.from_name
  138. package_distribution = Distribution.from_package_name
  139. class PackagePath(_PackagePath):
  140. """
  141. A filename relative to Conda's root (``sys.prefix``).
  142. This class inherits from :class:`pathlib.PurePosixPath` even on non-Posix OSs. To convert to a :class:`pathlib.Path`
  143. pointing to the real file, use the :meth:`locate` method.
  144. """
  145. def locate(self):
  146. """
  147. Return a path-like object for this path pointing to the file's true location.
  148. """
  149. return Path(sys.prefix) / self
  150. def walk_dependency_tree(initial: str, excludes: Iterable[str] = None) -> dict:
  151. """
  152. Collect a :class:`Distribution` and all direct and indirect dependencies of that distribution.
  153. Arguments:
  154. initial:
  155. Distribution name to collect from.
  156. excludes:
  157. Distributions to exclude.
  158. Returns:
  159. A ``{name: distribution}`` mapping where ``distribution`` is the output of
  160. :func:`conda_support.distribution(name) <distribution>`.
  161. """
  162. if excludes is not None:
  163. excludes = set(excludes)
  164. # Rather than use true recursion, mimic it with a to-do queue.
  165. from collections import deque
  166. done = {}
  167. names_to_do = deque([initial])
  168. while names_to_do:
  169. # Grab a distribution name from the to-do list.
  170. name = names_to_do.pop()
  171. try:
  172. # Collect and save it's metadata.
  173. done[name] = distribution = Distribution.from_name(name)
  174. logger.debug("Collected Conda distribution '%s', a dependency of '%s'.", name, initial)
  175. except ModuleNotFoundError:
  176. logger.warning(
  177. "Conda distribution '%s', dependency of '%s', was not found. "
  178. "If you installed this distribution with pip then you may ignore this warning.", name, initial
  179. )
  180. continue
  181. # For each dependency:
  182. for _name in distribution.dependencies:
  183. if _name in done:
  184. # Skip anything already done.
  185. continue
  186. if _name == name:
  187. # Avoid infinite recursion if a distribution depends on itself. This will probably never happen but I
  188. # certainly would not chance it.
  189. continue
  190. if excludes is not None and _name in excludes:
  191. # Do not recurse to excluded dependencies.
  192. continue
  193. names_to_do.append(_name)
  194. return done
  195. def _iter_distributions(name, dependencies, excludes):
  196. if dependencies:
  197. return walk_dependency_tree(name, excludes).values()
  198. else:
  199. return [Distribution.from_name(name)]
  200. def requires(name: str, strip_versions=False) -> List[str]:
  201. """
  202. List requirements of a distribution.
  203. Arguments:
  204. name:
  205. The name of the distribution.
  206. strip_versions:
  207. List only their names, not their version constraints.
  208. Returns:
  209. A list of distribution names.
  210. """
  211. if strip_versions:
  212. return distribution(name).dependencies
  213. return distribution(name).raw["depends"]
  214. def files(name: str, dependencies=False, excludes=None) -> List[PackagePath]:
  215. """
  216. List all files belonging to a distribution.
  217. Arguments:
  218. name:
  219. The name of the distribution.
  220. dependencies:
  221. Recursively collect files of dependencies too.
  222. excludes:
  223. Distributions to ignore if **dependencies** is true.
  224. Returns:
  225. All filenames belonging to the given distribution.
  226. With ``dependencies=False``, this is just a shortcut for::
  227. conda_support.distribution(name).files
  228. """
  229. return [file for dist in _iter_distributions(name, dependencies, excludes) for file in dist.files]
  230. if compat.is_win:
  231. lib_dir = PackagePath("Library", "bin")
  232. else:
  233. lib_dir = PackagePath("lib")
  234. def collect_dynamic_libs(name: str, dest: str = ".", dependencies: bool = True, excludes: Iterable[str] = None) -> List:
  235. """
  236. Collect DLLs for distribution **name**.
  237. Arguments:
  238. name:
  239. The distribution's project-name.
  240. dest:
  241. Target destination, defaults to ``'.'``.
  242. dependencies:
  243. Recursively collect libs for dependent distributions (recommended).
  244. excludes:
  245. Dependent distributions to skip, defaults to ``None``.
  246. Returns:
  247. List of DLLs in PyInstaller's ``(source, dest)`` format.
  248. This collects libraries only from Conda's shared ``lib`` (Unix) or ``Library/bin`` (Windows) folders. To collect
  249. from inside a distribution's installation use the regular :func:`PyInstaller.utils.hooks.collect_dynamic_libs`.
  250. """
  251. _files = []
  252. for file in files(name, dependencies, excludes):
  253. # A file is classified as a DLL if it lives inside the dedicated ``lib_dir`` DLL folder.
  254. if file.parent == lib_dir:
  255. _files.append((str(file.locate()), dest))
  256. return _files
  257. # --- Map packages to distributions and vice-versa ---
  258. def _get_package_name(file: PackagePath):
  259. """
  260. Determine the package name of a Python file in :data:`sys.path`.
  261. Arguments:
  262. file:
  263. A Python filename relative to Conda root (sys.prefix).
  264. Returns:
  265. Package name or None.
  266. This function only considers single file packages e.g. ``foo.py`` or top level ``foo/__init__.py``\\ s.
  267. Anything else is ignored (returning ``None``).
  268. """
  269. file = Path(file)
  270. # TODO: Handle PEP 420 namespace packages (which are missing `__init__` module). No such Conda PEP 420 namespace
  271. # packages are known.
  272. # Get top-level folders by finding parents of `__init__.xyz`s
  273. if file.stem == "__init__" and file.suffix in compat.ALL_SUFFIXES:
  274. file = file.parent
  275. elif file.suffix not in compat.ALL_SUFFIXES:
  276. # Keep single-file packages but skip DLLs, data and junk files.
  277. return
  278. # Check if this file/folder's parent is in ``sys.path`` i.e. it's directly importable. This intentionally excludes
  279. # submodules which would cause confusion because ``sys.prefix`` is in ``sys.path``, meaning that every file in an
  280. # Conda installation is a submodule.
  281. for prefix in PYTHONPATH_PREFIXES:
  282. if len(file.parts) != len(prefix.parts) + 1:
  283. # This check is redundant but speeds it up quite a bit.
  284. continue
  285. # There are no wildcards involved here. The use of ``fnmatch`` is simply to handle the `if case-insensitive
  286. # file system: use case-insensitive string matching.`
  287. if fnmatch.fnmatch(str(file.parent), str(prefix)):
  288. return file.stem
  289. # All the information we want is organised the wrong way.
  290. # We want to look up distribution based on package names, but we can only search for packages using distribution names.
  291. # And we would like to search for a distribution's json file, but, due to the noisy filenames of the jsons, we can only
  292. # find a json's distribution rather than a distribution's json.
  293. # So we have to read everything, then regroup distributions in the ways we want them grouped. This will likely be a
  294. # spectacular bottleneck on full-blown Conda (non miniconda) with 250+ packages by default at several GiBs. I suppose we
  295. # could cache this on a per-json basis if it gets too much.
  296. def _init_distributions():
  297. distributions = {}
  298. for path in CONDA_META_DIR.glob("*.json"):
  299. dist = Distribution(path)
  300. distributions[dist.name] = dist
  301. return distributions
  302. distributions = _init_distributions()
  303. def _init_packages():
  304. distributions_by_package = {}
  305. for distribution in distributions.values():
  306. for package in distribution.packages:
  307. distributions_by_package[package] = distribution
  308. return distributions_by_package
  309. distributions_by_package = _init_packages()