conda.py 14 KB

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