mkvenv.py 29 KB

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