mkvenv.py 27 KB

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