pyproject.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import importlib.util
  2. import os
  3. from collections import namedtuple
  4. from typing import Any, List, Optional
  5. from pip._vendor import tomli
  6. from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
  7. from pip._internal.exceptions import (
  8. InstallationError,
  9. InvalidPyProjectBuildRequires,
  10. MissingPyProjectBuildRequires,
  11. )
  12. def _is_list_of_str(obj: Any) -> bool:
  13. return isinstance(obj, list) and all(isinstance(item, str) for item in obj)
  14. def make_pyproject_path(unpacked_source_directory: str) -> str:
  15. return os.path.join(unpacked_source_directory, "pyproject.toml")
  16. BuildSystemDetails = namedtuple(
  17. "BuildSystemDetails", ["requires", "backend", "check", "backend_path"]
  18. )
  19. def load_pyproject_toml(
  20. use_pep517: Optional[bool], pyproject_toml: str, setup_py: str, req_name: str
  21. ) -> Optional[BuildSystemDetails]:
  22. """Load the pyproject.toml file.
  23. Parameters:
  24. use_pep517 - Has the user requested PEP 517 processing? None
  25. means the user hasn't explicitly specified.
  26. pyproject_toml - Location of the project's pyproject.toml file
  27. setup_py - Location of the project's setup.py file
  28. req_name - The name of the requirement we're processing (for
  29. error reporting)
  30. Returns:
  31. None if we should use the legacy code path, otherwise a tuple
  32. (
  33. requirements from pyproject.toml,
  34. name of PEP 517 backend,
  35. requirements we should check are installed after setting
  36. up the build environment
  37. directory paths to import the backend from (backend-path),
  38. relative to the project root.
  39. )
  40. """
  41. has_pyproject = os.path.isfile(pyproject_toml)
  42. has_setup = os.path.isfile(setup_py)
  43. if not has_pyproject and not has_setup:
  44. raise InstallationError(
  45. f"{req_name} does not appear to be a Python project: "
  46. f"neither 'setup.py' nor 'pyproject.toml' found."
  47. )
  48. if has_pyproject:
  49. with open(pyproject_toml, encoding="utf-8") as f:
  50. pp_toml = tomli.loads(f.read())
  51. build_system = pp_toml.get("build-system")
  52. else:
  53. build_system = None
  54. # The following cases must use PEP 517
  55. # We check for use_pep517 being non-None and falsey because that means
  56. # the user explicitly requested --no-use-pep517. The value 0 as
  57. # opposed to False can occur when the value is provided via an
  58. # environment variable or config file option (due to the quirk of
  59. # strtobool() returning an integer in pip's configuration code).
  60. if has_pyproject and not has_setup:
  61. if use_pep517 is not None and not use_pep517:
  62. raise InstallationError(
  63. "Disabling PEP 517 processing is invalid: "
  64. "project does not have a setup.py"
  65. )
  66. use_pep517 = True
  67. elif build_system and "build-backend" in build_system:
  68. if use_pep517 is not None and not use_pep517:
  69. raise InstallationError(
  70. "Disabling PEP 517 processing is invalid: "
  71. "project specifies a build backend of {} "
  72. "in pyproject.toml".format(build_system["build-backend"])
  73. )
  74. use_pep517 = True
  75. # If we haven't worked out whether to use PEP 517 yet,
  76. # and the user hasn't explicitly stated a preference,
  77. # we do so if the project has a pyproject.toml file
  78. # or if we cannot import setuptools or wheels.
  79. # We fallback to PEP 517 when without setuptools or without the wheel package,
  80. # so setuptools can be installed as a default build backend.
  81. # For more info see:
  82. # https://discuss.python.org/t/pip-without-setuptools-could-the-experience-be-improved/11810/9
  83. # https://github.com/pypa/pip/issues/8559
  84. elif use_pep517 is None:
  85. use_pep517 = (
  86. has_pyproject
  87. or not importlib.util.find_spec("setuptools")
  88. or not importlib.util.find_spec("wheel")
  89. )
  90. # At this point, we know whether we're going to use PEP 517.
  91. assert use_pep517 is not None
  92. # If we're using the legacy code path, there is nothing further
  93. # for us to do here.
  94. if not use_pep517:
  95. return None
  96. if build_system is None:
  97. # Either the user has a pyproject.toml with no build-system
  98. # section, or the user has no pyproject.toml, but has opted in
  99. # explicitly via --use-pep517.
  100. # In the absence of any explicit backend specification, we
  101. # assume the setuptools backend that most closely emulates the
  102. # traditional direct setup.py execution, and require wheel and
  103. # a version of setuptools that supports that backend.
  104. build_system = {
  105. "requires": ["setuptools>=40.8.0", "wheel"],
  106. "build-backend": "setuptools.build_meta:__legacy__",
  107. }
  108. # If we're using PEP 517, we have build system information (either
  109. # from pyproject.toml, or defaulted by the code above).
  110. # Note that at this point, we do not know if the user has actually
  111. # specified a backend, though.
  112. assert build_system is not None
  113. # Ensure that the build-system section in pyproject.toml conforms
  114. # to PEP 518.
  115. # Specifying the build-system table but not the requires key is invalid
  116. if "requires" not in build_system:
  117. raise MissingPyProjectBuildRequires(package=req_name)
  118. # Error out if requires is not a list of strings
  119. requires = build_system["requires"]
  120. if not _is_list_of_str(requires):
  121. raise InvalidPyProjectBuildRequires(
  122. package=req_name,
  123. reason="It is not a list of strings.",
  124. )
  125. # Each requirement must be valid as per PEP 508
  126. for requirement in requires:
  127. try:
  128. Requirement(requirement)
  129. except InvalidRequirement as error:
  130. raise InvalidPyProjectBuildRequires(
  131. package=req_name,
  132. reason=f"It contains an invalid requirement: {requirement!r}",
  133. ) from error
  134. backend = build_system.get("build-backend")
  135. backend_path = build_system.get("backend-path", [])
  136. check: List[str] = []
  137. if backend is None:
  138. # If the user didn't specify a backend, we assume they want to use
  139. # the setuptools backend. But we can't be sure they have included
  140. # a version of setuptools which supplies the backend. So we
  141. # make a note to check that this requirement is present once
  142. # we have set up the environment.
  143. # This is quite a lot of work to check for a very specific case. But
  144. # the problem is, that case is potentially quite common - projects that
  145. # adopted PEP 518 early for the ability to specify requirements to
  146. # execute setup.py, but never considered needing to mention the build
  147. # tools themselves. The original PEP 518 code had a similar check (but
  148. # implemented in a different way).
  149. backend = "setuptools.build_meta:__legacy__"
  150. check = ["setuptools>=40.8.0"]
  151. return BuildSystemDetails(requires, backend, check, backend_path)