2
0

mkvenv.py 27 KB

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