freeze.py 10 KB

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