mkvenv.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. """
  2. mkvenv - QEMU pyvenv bootstrapping utility
  3. usage: mkvenv [-h] command ...
  4. QEMU pyvenv bootstrapping utility
  5. options:
  6. -h, --help show this help message and exit
  7. Commands:
  8. command Description
  9. create create a venv
  10. post_init
  11. post-venv initialization
  12. ensure Ensure that the specified package is installed.
  13. ensuregroup
  14. Ensure that the specified package group is installed.
  15. --------------------------------------------------
  16. usage: mkvenv create [-h] target
  17. positional arguments:
  18. target Target directory to install virtual environment into.
  19. options:
  20. -h, --help show this help message and exit
  21. --------------------------------------------------
  22. usage: mkvenv post_init [-h]
  23. options:
  24. -h, --help show this help message and exit
  25. --------------------------------------------------
  26. usage: mkvenv ensure [-h] [--online] [--dir DIR] dep_spec...
  27. positional arguments:
  28. dep_spec PEP 508 Dependency specification, e.g. 'meson>=0.61.5'
  29. options:
  30. -h, --help show this help message and exit
  31. --online Install packages from PyPI, if necessary.
  32. --dir DIR Path to vendored packages where we may install from.
  33. --------------------------------------------------
  34. usage: mkvenv ensuregroup [-h] [--online] [--dir DIR] file group...
  35. positional arguments:
  36. file pointer to a TOML file
  37. group section name in the TOML file
  38. options:
  39. -h, --help show this help message and exit
  40. --online Install packages from PyPI, if necessary.
  41. --dir DIR Path to vendored packages where we may install from.
  42. """
  43. # Copyright (C) 2022-2023 Red Hat, Inc.
  44. #
  45. # Authors:
  46. # John Snow <jsnow@redhat.com>
  47. # Paolo Bonzini <pbonzini@redhat.com>
  48. #
  49. # This work is licensed under the terms of the GNU GPL, version 2 or
  50. # later. See the COPYING file in the top-level directory.
  51. import argparse
  52. from importlib.metadata import (
  53. Distribution,
  54. EntryPoint,
  55. PackageNotFoundError,
  56. distribution,
  57. version,
  58. )
  59. from importlib.util import find_spec
  60. import logging
  61. import os
  62. from pathlib import Path
  63. import re
  64. import shutil
  65. import site
  66. import subprocess
  67. import sys
  68. import sysconfig
  69. from types import SimpleNamespace
  70. from typing import (
  71. Any,
  72. Dict,
  73. Iterator,
  74. Optional,
  75. Sequence,
  76. Tuple,
  77. Union,
  78. )
  79. import venv
  80. # Try to load distlib, with a fallback to pip's vendored version.
  81. # HAVE_DISTLIB is checked below, just-in-time, so that mkvenv does not fail
  82. # outside the venv or before a potential call to ensurepip in checkpip().
  83. HAVE_DISTLIB = True
  84. try:
  85. import distlib.scripts
  86. import distlib.version
  87. except ImportError:
  88. try:
  89. # Reach into pip's cookie jar. pylint and flake8 don't understand
  90. # that these imports will be used via distlib.xxx.
  91. from pip._vendor import distlib
  92. import pip._vendor.distlib.scripts # noqa, pylint: disable=unused-import
  93. import pip._vendor.distlib.version # noqa, pylint: disable=unused-import
  94. except ImportError:
  95. HAVE_DISTLIB = False
  96. # Try to load tomllib, with a fallback to tomli.
  97. # HAVE_TOMLLIB is checked below, just-in-time, so that mkvenv does not fail
  98. # outside the venv or before a potential call to ensurepip in checkpip().
  99. HAVE_TOMLLIB = True
  100. try:
  101. import tomllib
  102. except ImportError:
  103. try:
  104. import tomli as tomllib
  105. except ImportError:
  106. HAVE_TOMLLIB = False
  107. # Do not add any mandatory dependencies from outside the stdlib:
  108. # This script *must* be usable standalone!
  109. DirType = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"]
  110. logger = logging.getLogger("mkvenv")
  111. def inside_a_venv() -> bool:
  112. """Returns True if it is executed inside of a virtual environment."""
  113. return sys.prefix != sys.base_prefix
  114. class Ouch(RuntimeError):
  115. """An Exception class we can't confuse with a builtin."""
  116. class QemuEnvBuilder(venv.EnvBuilder):
  117. """
  118. An extension of venv.EnvBuilder for building QEMU's configure-time venv.
  119. The primary difference is that it emulates a "nested" virtual
  120. environment when invoked from inside of an existing virtual
  121. environment by including packages from the parent. Also,
  122. "ensurepip" is replaced if possible with just recreating pip's
  123. console_scripts inside the virtual environment.
  124. Parameters for base class init:
  125. - system_site_packages: bool = False
  126. - clear: bool = False
  127. - symlinks: bool = False
  128. - upgrade: bool = False
  129. - with_pip: bool = False
  130. - prompt: Optional[str] = None
  131. - upgrade_deps: bool = False (Since 3.9)
  132. """
  133. def __init__(self, *args: Any, **kwargs: Any) -> None:
  134. logger.debug("QemuEnvBuilder.__init__(...)")
  135. # For nested venv emulation:
  136. self.use_parent_packages = False
  137. if inside_a_venv():
  138. # Include parent packages only if we're in a venv and
  139. # system_site_packages was True.
  140. self.use_parent_packages = kwargs.pop(
  141. "system_site_packages", False
  142. )
  143. # Include system_site_packages only when the parent,
  144. # The venv we are currently in, also does so.
  145. kwargs["system_site_packages"] = sys.base_prefix in site.PREFIXES
  146. # ensurepip is slow: venv creation can be very fast for cases where
  147. # we allow the use of system_site_packages. Therefore, ensurepip is
  148. # replaced with our own script generation once the virtual environment
  149. # is setup.
  150. self.want_pip = kwargs.get("with_pip", False)
  151. if self.want_pip:
  152. if (
  153. kwargs.get("system_site_packages", False)
  154. and not need_ensurepip()
  155. ):
  156. kwargs["with_pip"] = False
  157. else:
  158. check_ensurepip()
  159. super().__init__(*args, **kwargs)
  160. # Make the context available post-creation:
  161. self._context: Optional[SimpleNamespace] = None
  162. def get_parent_libpath(self) -> Optional[str]:
  163. """Return the libpath of the parent venv, if applicable."""
  164. if self.use_parent_packages:
  165. return sysconfig.get_path("purelib")
  166. return None
  167. @staticmethod
  168. def compute_venv_libpath(context: SimpleNamespace) -> str:
  169. """
  170. Compatibility wrapper for context.lib_path for Python < 3.12
  171. """
  172. # Python 3.12+, not strictly necessary because it's documented
  173. # to be the same as 3.10 code below:
  174. if sys.version_info >= (3, 12):
  175. return context.lib_path
  176. # Python 3.10+
  177. if "venv" in sysconfig.get_scheme_names():
  178. lib_path = sysconfig.get_path(
  179. "purelib", scheme="venv", vars={"base": context.env_dir}
  180. )
  181. assert lib_path is not None
  182. return lib_path
  183. # For Python <= 3.9 we need to hardcode this. Fortunately the
  184. # code below was the same in Python 3.6-3.10, so there is only
  185. # one case.
  186. if sys.platform == "win32":
  187. return os.path.join(context.env_dir, "Lib", "site-packages")
  188. return os.path.join(
  189. context.env_dir,
  190. "lib",
  191. "python%d.%d" % sys.version_info[:2],
  192. "site-packages",
  193. )
  194. def ensure_directories(self, env_dir: DirType) -> SimpleNamespace:
  195. logger.debug("ensure_directories(env_dir=%s)", env_dir)
  196. self._context = super().ensure_directories(env_dir)
  197. return self._context
  198. def create(self, env_dir: DirType) -> None:
  199. logger.debug("create(env_dir=%s)", env_dir)
  200. super().create(env_dir)
  201. assert self._context is not None
  202. self.post_post_setup(self._context)
  203. def post_post_setup(self, context: SimpleNamespace) -> None:
  204. """
  205. The final, final hook. Enter the venv and run commands inside of it.
  206. """
  207. if self.use_parent_packages:
  208. # We're inside of a venv and we want to include the parent
  209. # venv's packages.
  210. parent_libpath = self.get_parent_libpath()
  211. assert parent_libpath is not None
  212. logger.debug("parent_libpath: %s", parent_libpath)
  213. our_libpath = self.compute_venv_libpath(context)
  214. logger.debug("our_libpath: %s", our_libpath)
  215. pth_file = os.path.join(our_libpath, "nested.pth")
  216. with open(pth_file, "w", encoding="UTF-8") as file:
  217. file.write(parent_libpath + os.linesep)
  218. if self.want_pip:
  219. args = [
  220. context.env_exe,
  221. __file__,
  222. "post_init",
  223. ]
  224. subprocess.run(args, check=True)
  225. def get_value(self, field: str) -> str:
  226. """
  227. Get a string value from the context namespace after a call to build.
  228. For valid field names, see:
  229. https://docs.python.org/3/library/venv.html#venv.EnvBuilder.ensure_directories
  230. """
  231. ret = getattr(self._context, field)
  232. assert isinstance(ret, str)
  233. return ret
  234. def need_ensurepip() -> bool:
  235. """
  236. Tests for the presence of setuptools and pip.
  237. :return: `True` if we do not detect both packages.
  238. """
  239. # Don't try to actually import them, it's fraught with danger:
  240. # https://github.com/pypa/setuptools/issues/2993
  241. if find_spec("setuptools") and find_spec("pip"):
  242. return False
  243. return True
  244. def check_ensurepip() -> None:
  245. """
  246. Check that we have ensurepip.
  247. Raise a fatal exception with a helpful hint if it isn't available.
  248. """
  249. if not find_spec("ensurepip"):
  250. msg = (
  251. "Python's ensurepip module is not found.\n"
  252. "It's normally part of the Python standard library, "
  253. "maybe your distribution packages it separately?\n"
  254. "Either install ensurepip, or alleviate the need for it in the "
  255. "first place by installing pip and setuptools for "
  256. f"'{sys.executable}'.\n"
  257. "(Hint: Debian puts ensurepip in its python3-venv package.)"
  258. )
  259. raise Ouch(msg)
  260. # ensurepip uses pyexpat, which can also go missing on us:
  261. if not find_spec("pyexpat"):
  262. msg = (
  263. "Python's pyexpat module is not found.\n"
  264. "It's normally part of the Python standard library, "
  265. "maybe your distribution packages it separately?\n"
  266. "Either install pyexpat, or alleviate the need for it in the "
  267. "first place by installing pip and setuptools for "
  268. f"'{sys.executable}'.\n\n"
  269. "(Hint: NetBSD's pkgsrc debundles this to e.g. 'py310-expat'.)"
  270. )
  271. raise Ouch(msg)
  272. def make_venv( # pylint: disable=too-many-arguments
  273. env_dir: Union[str, Path],
  274. system_site_packages: bool = False,
  275. clear: bool = True,
  276. symlinks: Optional[bool] = None,
  277. with_pip: bool = True,
  278. ) -> None:
  279. """
  280. Create a venv using `QemuEnvBuilder`.
  281. This is analogous to the `venv.create` module-level convenience
  282. function that is part of the Python stdblib, except it uses
  283. `QemuEnvBuilder` instead.
  284. :param env_dir: The directory to create/install to.
  285. :param system_site_packages:
  286. Allow inheriting packages from the system installation.
  287. :param clear: When True, fully remove any prior venv and files.
  288. :param symlinks:
  289. Whether to use symlinks to the target interpreter or not. If
  290. left unspecified, it will use symlinks except on Windows to
  291. match behavior with the "venv" CLI tool.
  292. :param with_pip:
  293. Whether to install "pip" binaries or not.
  294. """
  295. logger.debug(
  296. "%s: make_venv(env_dir=%s, system_site_packages=%s, "
  297. "clear=%s, symlinks=%s, with_pip=%s)",
  298. __file__,
  299. str(env_dir),
  300. system_site_packages,
  301. clear,
  302. symlinks,
  303. with_pip,
  304. )
  305. if symlinks is None:
  306. # Default behavior of standard venv CLI
  307. symlinks = os.name != "nt"
  308. builder = QemuEnvBuilder(
  309. system_site_packages=system_site_packages,
  310. clear=clear,
  311. symlinks=symlinks,
  312. with_pip=with_pip,
  313. )
  314. style = "non-isolated" if builder.system_site_packages else "isolated"
  315. nested = ""
  316. if builder.use_parent_packages:
  317. nested = f"(with packages from '{builder.get_parent_libpath()}') "
  318. print(
  319. f"mkvenv: Creating {style} virtual environment"
  320. f" {nested}at '{str(env_dir)}'",
  321. file=sys.stderr,
  322. )
  323. try:
  324. logger.debug("Invoking builder.create()")
  325. try:
  326. builder.create(str(env_dir))
  327. except SystemExit as exc:
  328. # Some versions of the venv module raise SystemExit; *nasty*!
  329. # We want the exception that prompted it. It might be a subprocess
  330. # error that has output we *really* want to see.
  331. logger.debug("Intercepted SystemExit from EnvBuilder.create()")
  332. raise exc.__cause__ or exc.__context__ or exc
  333. logger.debug("builder.create() finished")
  334. except subprocess.CalledProcessError as exc:
  335. logger.error("mkvenv subprocess failed:")
  336. logger.error("cmd: %s", exc.cmd)
  337. logger.error("returncode: %d", exc.returncode)
  338. def _stringify(data: Union[str, bytes]) -> str:
  339. if isinstance(data, bytes):
  340. return data.decode()
  341. return data
  342. lines = []
  343. if exc.stdout:
  344. lines.append("========== stdout ==========")
  345. lines.append(_stringify(exc.stdout))
  346. lines.append("============================")
  347. if exc.stderr:
  348. lines.append("========== stderr ==========")
  349. lines.append(_stringify(exc.stderr))
  350. lines.append("============================")
  351. if lines:
  352. logger.error(os.linesep.join(lines))
  353. raise Ouch("VENV creation subprocess failed.") from exc
  354. # print the python executable to stdout for configure.
  355. print(builder.get_value("env_exe"))
  356. def _get_entry_points(packages: Sequence[str]) -> Iterator[str]:
  357. def _generator() -> Iterator[str]:
  358. for package in packages:
  359. try:
  360. entry_points: Iterator[EntryPoint] = \
  361. iter(distribution(package).entry_points)
  362. except PackageNotFoundError:
  363. continue
  364. # The EntryPoints type is only available in 3.10+,
  365. # treat this as a vanilla list and filter it ourselves.
  366. entry_points = filter(
  367. lambda ep: ep.group == "console_scripts", entry_points
  368. )
  369. for entry_point in entry_points:
  370. yield f"{entry_point.name} = {entry_point.value}"
  371. return _generator()
  372. def generate_console_scripts(
  373. packages: Sequence[str],
  374. python_path: Optional[str] = None,
  375. bin_path: Optional[str] = None,
  376. ) -> None:
  377. """
  378. Generate script shims for console_script entry points in @packages.
  379. """
  380. if python_path is None:
  381. python_path = sys.executable
  382. if bin_path is None:
  383. bin_path = sysconfig.get_path("scripts")
  384. assert bin_path is not None
  385. logger.debug(
  386. "generate_console_scripts(packages=%s, python_path=%s, bin_path=%s)",
  387. packages,
  388. python_path,
  389. bin_path,
  390. )
  391. if not packages:
  392. return
  393. maker = distlib.scripts.ScriptMaker(None, bin_path)
  394. maker.variants = {""}
  395. maker.clobber = False
  396. for entry_point in _get_entry_points(packages):
  397. for filename in maker.make(entry_point):
  398. logger.debug("wrote console_script '%s'", filename)
  399. def pkgname_from_depspec(dep_spec: str) -> str:
  400. """
  401. Parse package name out of a PEP-508 depspec.
  402. See https://peps.python.org/pep-0508/#names
  403. """
  404. match = re.match(
  405. r"^([A-Z0-9]([A-Z0-9._-]*[A-Z0-9])?)", dep_spec, re.IGNORECASE
  406. )
  407. if not match:
  408. raise ValueError(
  409. f"dep_spec '{dep_spec}'"
  410. " does not appear to contain a valid package name"
  411. )
  412. return match.group(0)
  413. def _path_is_prefix(prefix: Optional[str], path: str) -> bool:
  414. try:
  415. return (
  416. prefix is not None and os.path.commonpath([prefix, path]) == prefix
  417. )
  418. except ValueError:
  419. return False
  420. def _is_system_package(dist: Distribution) -> bool:
  421. path = str(dist.locate_file("."))
  422. return not (
  423. _path_is_prefix(sysconfig.get_path("purelib"), path)
  424. or _path_is_prefix(sysconfig.get_path("platlib"), path)
  425. )
  426. def diagnose(
  427. dep_spec: str,
  428. online: bool,
  429. wheels_dir: Optional[Union[str, Path]],
  430. prog: Optional[str],
  431. ) -> Tuple[str, bool]:
  432. """
  433. Offer a summary to the user as to why a package failed to be installed.
  434. :param dep_spec: The package we tried to ensure, e.g. 'meson>=0.61.5'
  435. :param online: Did we allow PyPI access?
  436. :param prog:
  437. Optionally, a shell program name that can be used as a
  438. bellwether to detect if this program is installed elsewhere on
  439. the system. This is used to offer advice when a program is
  440. detected for a different python version.
  441. :param wheels_dir:
  442. Optionally, a directory that was searched for vendored packages.
  443. """
  444. # pylint: disable=too-many-branches
  445. # Some errors are not particularly serious
  446. bad = False
  447. pkg_name = pkgname_from_depspec(dep_spec)
  448. pkg_version: Optional[str] = None
  449. try:
  450. pkg_version = version(pkg_name)
  451. except PackageNotFoundError:
  452. pass
  453. lines = []
  454. if pkg_version:
  455. lines.append(
  456. f"Python package '{pkg_name}' version '{pkg_version}' was found,"
  457. " but isn't suitable."
  458. )
  459. else:
  460. lines.append(
  461. f"Python package '{pkg_name}' was not found nor installed."
  462. )
  463. if wheels_dir:
  464. lines.append(
  465. "No suitable version found in, or failed to install from"
  466. f" '{wheels_dir}'."
  467. )
  468. bad = True
  469. if online:
  470. lines.append("A suitable version could not be obtained from PyPI.")
  471. bad = True
  472. else:
  473. lines.append(
  474. "mkvenv was configured to operate offline and did not check PyPI."
  475. )
  476. if prog and not pkg_version:
  477. which = shutil.which(prog)
  478. if which:
  479. if sys.base_prefix in site.PREFIXES:
  480. pypath = Path(sys.executable).resolve()
  481. lines.append(
  482. f"'{prog}' was detected on your system at '{which}', "
  483. f"but the Python package '{pkg_name}' was not found by "
  484. f"this Python interpreter ('{pypath}'). "
  485. f"Typically this means that '{prog}' has been installed "
  486. "against a different Python interpreter on your system."
  487. )
  488. else:
  489. lines.append(
  490. f"'{prog}' was detected on your system at '{which}', "
  491. "but the build is using an isolated virtual environment."
  492. )
  493. bad = True
  494. lines = [f" • {line}" for line in lines]
  495. if bad:
  496. lines.insert(0, f"Could not provide build dependency '{dep_spec}':")
  497. else:
  498. lines.insert(0, f"'{dep_spec}' not found:")
  499. return os.linesep.join(lines), bad
  500. def pip_install(
  501. args: Sequence[str],
  502. online: bool = False,
  503. wheels_dir: Optional[Union[str, Path]] = None,
  504. ) -> None:
  505. """
  506. Use pip to install a package or package(s) as specified in @args.
  507. """
  508. loud = bool(
  509. os.environ.get("DEBUG")
  510. or os.environ.get("GITLAB_CI")
  511. or os.environ.get("V")
  512. )
  513. full_args = [
  514. sys.executable,
  515. "-m",
  516. "pip",
  517. "install",
  518. "--disable-pip-version-check",
  519. "-v" if loud else "-q",
  520. ]
  521. if not online:
  522. full_args += ["--no-index"]
  523. if wheels_dir:
  524. full_args += ["--find-links", f"file://{str(wheels_dir)}"]
  525. full_args += list(args)
  526. subprocess.run(
  527. full_args,
  528. check=True,
  529. )
  530. def _make_version_constraint(info: Dict[str, str], install: bool) -> str:
  531. """
  532. Construct the version constraint part of a PEP 508 dependency
  533. specification (for example '>=0.61.5') from the accepted and
  534. installed keys of the provided dictionary.
  535. :param info: A dictionary corresponding to a TOML key-value list.
  536. :param install: True generates install constraints, False generates
  537. presence constraints
  538. """
  539. if install and "installed" in info:
  540. return "==" + info["installed"]
  541. dep_spec = info.get("accepted", "")
  542. dep_spec = dep_spec.strip()
  543. # Double check that they didn't just use a version number
  544. if dep_spec and dep_spec[0] not in "!~><=(":
  545. raise Ouch(
  546. "invalid dependency specifier " + dep_spec + " in dependency file"
  547. )
  548. return dep_spec
  549. def _do_ensure(
  550. group: Dict[str, Dict[str, str]],
  551. online: bool = False,
  552. wheels_dir: Optional[Union[str, Path]] = None,
  553. ) -> Optional[Tuple[str, bool]]:
  554. """
  555. Use pip to ensure we have the packages specified in @group.
  556. If the packages are already installed, do nothing. If online and
  557. wheels_dir are both provided, prefer packages found in wheels_dir
  558. first before connecting to PyPI.
  559. :param group: A dictionary of dictionaries, corresponding to a
  560. section in a pythondeps.toml file.
  561. :param online: If True, fall back to PyPI.
  562. :param wheels_dir: If specified, search this path for packages.
  563. """
  564. absent = []
  565. present = []
  566. canary = None
  567. for name, info in group.items():
  568. constraint = _make_version_constraint(info, False)
  569. matcher = distlib.version.LegacyMatcher(name + constraint)
  570. print(f"mkvenv: checking for {matcher}", file=sys.stderr)
  571. dist: Optional[Distribution] = None
  572. try:
  573. dist = distribution(matcher.name)
  574. except PackageNotFoundError:
  575. pass
  576. if (
  577. dist is None
  578. # Always pass installed package to pip, so that they can be
  579. # updated if the requested version changes
  580. or not _is_system_package(dist)
  581. or not matcher.match(distlib.version.LegacyVersion(dist.version))
  582. ):
  583. absent.append(name + _make_version_constraint(info, True))
  584. if len(absent) == 1:
  585. canary = info.get("canary", None)
  586. else:
  587. logger.info("found %s %s", name, dist.version)
  588. present.append(name)
  589. if present:
  590. generate_console_scripts(present)
  591. if absent:
  592. if online or wheels_dir:
  593. # Some packages are missing or aren't a suitable version,
  594. # install a suitable (possibly vendored) package.
  595. print(f"mkvenv: installing {', '.join(absent)}", file=sys.stderr)
  596. try:
  597. pip_install(args=absent, online=online, wheels_dir=wheels_dir)
  598. return None
  599. except subprocess.CalledProcessError:
  600. pass
  601. return diagnose(
  602. absent[0],
  603. online,
  604. wheels_dir,
  605. canary,
  606. )
  607. return None
  608. def ensure(
  609. dep_specs: Sequence[str],
  610. online: bool = False,
  611. wheels_dir: Optional[Union[str, Path]] = None,
  612. prog: Optional[str] = None,
  613. ) -> None:
  614. """
  615. Use pip to ensure we have the package specified by @dep_specs.
  616. If the package is already installed, do nothing. If online and
  617. wheels_dir are both provided, prefer packages found in wheels_dir
  618. first before connecting to PyPI.
  619. :param dep_specs:
  620. PEP 508 dependency specifications. e.g. ['meson>=0.61.5'].
  621. :param online: If True, fall back to PyPI.
  622. :param wheels_dir: If specified, search this path for packages.
  623. :param prog:
  624. If specified, use this program name for error diagnostics that will
  625. be presented to the user. e.g., 'sphinx-build' can be used as a
  626. bellwether for the presence of 'sphinx'.
  627. """
  628. if not HAVE_DISTLIB:
  629. raise Ouch("a usable distlib could not be found, please install it")
  630. # Convert the depspecs to a dictionary, as if they came
  631. # from a section in a pythondeps.toml file
  632. group: Dict[str, Dict[str, str]] = {}
  633. for spec in dep_specs:
  634. name = distlib.version.LegacyMatcher(spec).name
  635. group[name] = {}
  636. spec = spec.strip()
  637. pos = len(name)
  638. ver = spec[pos:].strip()
  639. if ver:
  640. group[name]["accepted"] = ver
  641. if prog:
  642. group[name]["canary"] = prog
  643. prog = None
  644. result = _do_ensure(group, online, wheels_dir)
  645. if result:
  646. # Well, that's not good.
  647. if result[1]:
  648. raise Ouch(result[0])
  649. raise SystemExit(f"\n{result[0]}\n\n")
  650. def _parse_groups(file: str) -> Dict[str, Dict[str, Any]]:
  651. if not HAVE_TOMLLIB:
  652. if sys.version_info < (3, 11):
  653. raise Ouch("found no usable tomli, please install it")
  654. raise Ouch(
  655. "Python >=3.11 does not have tomllib... what have you done!?"
  656. )
  657. # Use loads() to support both tomli v1.2.x (Ubuntu 22.04,
  658. # Debian bullseye-backports) and v2.0.x
  659. with open(file, "r", encoding="ascii") as depfile:
  660. contents = depfile.read()
  661. return tomllib.loads(contents) # type: ignore
  662. def ensure_group(
  663. file: str,
  664. groups: Sequence[str],
  665. online: bool = False,
  666. wheels_dir: Optional[Union[str, Path]] = None,
  667. ) -> None:
  668. """
  669. Use pip to ensure we have the package specified by @dep_specs.
  670. If the package is already installed, do nothing. If online and
  671. wheels_dir are both provided, prefer packages found in wheels_dir
  672. first before connecting to PyPI.
  673. :param dep_specs:
  674. PEP 508 dependency specifications. e.g. ['meson>=0.61.5'].
  675. :param online: If True, fall back to PyPI.
  676. :param wheels_dir: If specified, search this path for packages.
  677. """
  678. if not HAVE_DISTLIB:
  679. raise Ouch("found no usable distlib, please install it")
  680. parsed_deps = _parse_groups(file)
  681. to_install: Dict[str, Dict[str, str]] = {}
  682. for group in groups:
  683. try:
  684. to_install.update(parsed_deps[group])
  685. except KeyError as exc:
  686. raise Ouch(f"group {group} not defined") from exc
  687. result = _do_ensure(to_install, online, wheels_dir)
  688. if result:
  689. # Well, that's not good.
  690. if result[1]:
  691. raise Ouch(result[0])
  692. raise SystemExit(f"\n{result[0]}\n\n")
  693. def post_venv_setup() -> None:
  694. """
  695. This is intended to be run *inside the venv* after it is created.
  696. """
  697. logger.debug("post_venv_setup()")
  698. # Generate a 'pip' script so the venv is usable in a normal
  699. # way from the CLI. This only happens when we inherited pip from a
  700. # parent/system-site and haven't run ensurepip in some way.
  701. generate_console_scripts(["pip"])
  702. def _add_create_subcommand(subparsers: Any) -> None:
  703. subparser = subparsers.add_parser("create", help="create a venv")
  704. subparser.add_argument(
  705. "target",
  706. type=str,
  707. action="store",
  708. help="Target directory to install virtual environment into.",
  709. )
  710. def _add_post_init_subcommand(subparsers: Any) -> None:
  711. subparsers.add_parser("post_init", help="post-venv initialization")
  712. def _add_ensuregroup_subcommand(subparsers: Any) -> None:
  713. subparser = subparsers.add_parser(
  714. "ensuregroup",
  715. help="Ensure that the specified package group is installed.",
  716. )
  717. subparser.add_argument(
  718. "--online",
  719. action="store_true",
  720. help="Install packages from PyPI, if necessary.",
  721. )
  722. subparser.add_argument(
  723. "--dir",
  724. type=str,
  725. action="store",
  726. help="Path to vendored packages where we may install from.",
  727. )
  728. subparser.add_argument(
  729. "file",
  730. type=str,
  731. action="store",
  732. help=("Path to a TOML file describing package groups"),
  733. )
  734. subparser.add_argument(
  735. "group",
  736. type=str,
  737. action="store",
  738. help="One or more package group names",
  739. nargs="+",
  740. )
  741. def _add_ensure_subcommand(subparsers: Any) -> None:
  742. subparser = subparsers.add_parser(
  743. "ensure", help="Ensure that the specified package is installed."
  744. )
  745. subparser.add_argument(
  746. "--online",
  747. action="store_true",
  748. help="Install packages from PyPI, if necessary.",
  749. )
  750. subparser.add_argument(
  751. "--dir",
  752. type=str,
  753. action="store",
  754. help="Path to vendored packages where we may install from.",
  755. )
  756. subparser.add_argument(
  757. "--diagnose",
  758. type=str,
  759. action="store",
  760. help=(
  761. "Name of a shell utility to use for "
  762. "diagnostics if this command fails."
  763. ),
  764. )
  765. subparser.add_argument(
  766. "dep_specs",
  767. type=str,
  768. action="store",
  769. help="PEP 508 Dependency specification, e.g. 'meson>=0.61.5'",
  770. nargs="+",
  771. )
  772. def main() -> int:
  773. """CLI interface to make_qemu_venv. See module docstring."""
  774. if os.environ.get("DEBUG") or os.environ.get("GITLAB_CI"):
  775. # You're welcome.
  776. logging.basicConfig(level=logging.DEBUG)
  777. else:
  778. if os.environ.get("V"):
  779. logging.basicConfig(level=logging.INFO)
  780. parser = argparse.ArgumentParser(
  781. prog="mkvenv",
  782. description="QEMU pyvenv bootstrapping utility",
  783. )
  784. subparsers = parser.add_subparsers(
  785. title="Commands",
  786. dest="command",
  787. required=True,
  788. metavar="command",
  789. help="Description",
  790. )
  791. _add_create_subcommand(subparsers)
  792. _add_post_init_subcommand(subparsers)
  793. _add_ensure_subcommand(subparsers)
  794. _add_ensuregroup_subcommand(subparsers)
  795. args = parser.parse_args()
  796. try:
  797. if args.command == "create":
  798. make_venv(
  799. args.target,
  800. system_site_packages=True,
  801. clear=True,
  802. )
  803. if args.command == "post_init":
  804. post_venv_setup()
  805. if args.command == "ensure":
  806. ensure(
  807. dep_specs=args.dep_specs,
  808. online=args.online,
  809. wheels_dir=args.dir,
  810. prog=args.diagnose,
  811. )
  812. if args.command == "ensuregroup":
  813. ensure_group(
  814. file=args.file,
  815. groups=args.group,
  816. online=args.online,
  817. wheels_dir=args.dir,
  818. )
  819. logger.debug("mkvenv.py %s: exiting", args.command)
  820. except Ouch as exc:
  821. print("\n*** Ouch! ***\n", file=sys.stderr)
  822. print(str(exc), "\n\n", file=sys.stderr)
  823. return 1
  824. except SystemExit:
  825. raise
  826. except: # pylint: disable=bare-except
  827. logger.exception("mkvenv did not complete successfully:")
  828. return 2
  829. return 0
  830. if __name__ == "__main__":
  831. sys.exit(main())