freeze.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import collections
  2. import logging
  3. import os
  4. from typing import Container, Dict, Generator, Iterable, List, NamedTuple, Optional, Set
  5. from pip._vendor.packaging.utils import canonicalize_name
  6. from pip._vendor.packaging.version import InvalidVersion
  7. from pip._internal.exceptions import BadCommand, InstallationError
  8. from pip._internal.metadata import BaseDistribution, get_environment
  9. from pip._internal.req.constructors import (
  10. install_req_from_editable,
  11. install_req_from_line,
  12. )
  13. from pip._internal.req.req_file import COMMENT_RE
  14. from pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference
  15. logger = logging.getLogger(__name__)
  16. class _EditableInfo(NamedTuple):
  17. requirement: str
  18. comments: List[str]
  19. def freeze(
  20. requirement: Optional[List[str]] = None,
  21. local_only: bool = False,
  22. user_only: bool = False,
  23. paths: Optional[List[str]] = None,
  24. isolated: bool = False,
  25. exclude_editable: bool = False,
  26. skip: Container[str] = (),
  27. ) -> Generator[str, None, None]:
  28. installations: Dict[str, FrozenRequirement] = {}
  29. dists = get_environment(paths).iter_installed_distributions(
  30. local_only=local_only,
  31. skip=(),
  32. user_only=user_only,
  33. )
  34. for dist in dists:
  35. req = FrozenRequirement.from_dist(dist)
  36. if exclude_editable and req.editable:
  37. continue
  38. installations[req.canonical_name] = req
  39. if requirement:
  40. # the options that don't get turned into an InstallRequirement
  41. # should only be emitted once, even if the same option is in multiple
  42. # requirements files, so we need to keep track of what has been emitted
  43. # so that we don't emit it again if it's seen again
  44. emitted_options: Set[str] = set()
  45. # keep track of which files a requirement is in so that we can
  46. # give an accurate warning if a requirement appears multiple times.
  47. req_files: Dict[str, List[str]] = collections.defaultdict(list)
  48. for req_file_path in requirement:
  49. with open(req_file_path) as req_file:
  50. for line in req_file:
  51. if (
  52. not line.strip()
  53. or line.strip().startswith("#")
  54. or line.startswith(
  55. (
  56. "-r",
  57. "--requirement",
  58. "-f",
  59. "--find-links",
  60. "-i",
  61. "--index-url",
  62. "--pre",
  63. "--trusted-host",
  64. "--process-dependency-links",
  65. "--extra-index-url",
  66. "--use-feature",
  67. )
  68. )
  69. ):
  70. line = line.rstrip()
  71. if line not in emitted_options:
  72. emitted_options.add(line)
  73. yield line
  74. continue
  75. if line.startswith("-e") or line.startswith("--editable"):
  76. if line.startswith("-e"):
  77. line = line[2:].strip()
  78. else:
  79. line = line[len("--editable") :].strip().lstrip("=")
  80. line_req = install_req_from_editable(
  81. line,
  82. isolated=isolated,
  83. )
  84. else:
  85. line_req = install_req_from_line(
  86. COMMENT_RE.sub("", line).strip(),
  87. isolated=isolated,
  88. )
  89. if not line_req.name:
  90. logger.info(
  91. "Skipping line in requirement file [%s] because "
  92. "it's not clear what it would install: %s",
  93. req_file_path,
  94. line.strip(),
  95. )
  96. logger.info(
  97. " (add #egg=PackageName to the URL to avoid"
  98. " this warning)"
  99. )
  100. else:
  101. line_req_canonical_name = canonicalize_name(line_req.name)
  102. if line_req_canonical_name not in installations:
  103. # either it's not installed, or it is installed
  104. # but has been processed already
  105. if not req_files[line_req.name]:
  106. logger.warning(
  107. "Requirement file [%s] contains %s, but "
  108. "package %r is not installed",
  109. req_file_path,
  110. COMMENT_RE.sub("", line).strip(),
  111. line_req.name,
  112. )
  113. else:
  114. req_files[line_req.name].append(req_file_path)
  115. else:
  116. yield str(installations[line_req_canonical_name]).rstrip()
  117. del installations[line_req_canonical_name]
  118. req_files[line_req.name].append(req_file_path)
  119. # Warn about requirements that were included multiple times (in a
  120. # single requirements file or in different requirements files).
  121. for name, files in req_files.items():
  122. if len(files) > 1:
  123. logger.warning(
  124. "Requirement %s included multiple times [%s]",
  125. name,
  126. ", ".join(sorted(set(files))),
  127. )
  128. yield ("## The following requirements were added by pip freeze:")
  129. for installation in sorted(installations.values(), key=lambda x: x.name.lower()):
  130. if installation.canonical_name not in skip:
  131. yield str(installation).rstrip()
  132. def _format_as_name_version(dist: BaseDistribution) -> str:
  133. try:
  134. dist_version = dist.version
  135. except InvalidVersion:
  136. # legacy version
  137. return f"{dist.raw_name}==={dist.raw_version}"
  138. else:
  139. return f"{dist.raw_name}=={dist_version}"
  140. def _get_editable_info(dist: BaseDistribution) -> _EditableInfo:
  141. """
  142. Compute and return values (req, comments) for use in
  143. FrozenRequirement.from_dist().
  144. """
  145. editable_project_location = dist.editable_project_location
  146. assert editable_project_location
  147. location = os.path.normcase(os.path.abspath(editable_project_location))
  148. from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs
  149. vcs_backend = vcs.get_backend_for_dir(location)
  150. if vcs_backend is None:
  151. display = _format_as_name_version(dist)
  152. logger.debug(
  153. 'No VCS found for editable requirement "%s" in: %r',
  154. display,
  155. location,
  156. )
  157. return _EditableInfo(
  158. requirement=location,
  159. comments=[f"# Editable install with no version control ({display})"],
  160. )
  161. vcs_name = type(vcs_backend).__name__
  162. try:
  163. req = vcs_backend.get_src_requirement(location, dist.raw_name)
  164. except RemoteNotFoundError:
  165. display = _format_as_name_version(dist)
  166. return _EditableInfo(
  167. requirement=location,
  168. comments=[f"# Editable {vcs_name} install with no remote ({display})"],
  169. )
  170. except RemoteNotValidError as ex:
  171. display = _format_as_name_version(dist)
  172. return _EditableInfo(
  173. requirement=location,
  174. comments=[
  175. f"# Editable {vcs_name} install ({display}) with either a deleted "
  176. f"local remote or invalid URI:",
  177. f"# '{ex.url}'",
  178. ],
  179. )
  180. except BadCommand:
  181. logger.warning(
  182. "cannot determine version of editable source in %s "
  183. "(%s command not found in path)",
  184. location,
  185. vcs_backend.name,
  186. )
  187. return _EditableInfo(requirement=location, comments=[])
  188. except InstallationError as exc:
  189. logger.warning("Error when trying to get requirement for VCS system %s", exc)
  190. else:
  191. return _EditableInfo(requirement=req, comments=[])
  192. logger.warning("Could not determine repository location of %s", location)
  193. return _EditableInfo(
  194. requirement=location,
  195. comments=["## !! Could not determine repository location"],
  196. )
  197. class FrozenRequirement:
  198. def __init__(
  199. self,
  200. name: str,
  201. req: str,
  202. editable: bool,
  203. comments: Iterable[str] = (),
  204. ) -> None:
  205. self.name = name
  206. self.canonical_name = canonicalize_name(name)
  207. self.req = req
  208. self.editable = editable
  209. self.comments = comments
  210. @classmethod
  211. def from_dist(cls, dist: BaseDistribution) -> "FrozenRequirement":
  212. editable = dist.editable
  213. if editable:
  214. req, comments = _get_editable_info(dist)
  215. else:
  216. comments = []
  217. direct_url = dist.direct_url
  218. if direct_url:
  219. # if PEP 610 metadata is present, use it
  220. req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name)
  221. else:
  222. # name==version requirement
  223. req = _format_as_name_version(dist)
  224. return cls(dist.raw_name, req, editable, comments=comments)
  225. def __str__(self) -> str:
  226. req = self.req
  227. if self.editable:
  228. req = f"-e {req}"
  229. return "\n".join(list(self.comments) + [str(req)]) + "\n"