freeze.py 10 KB

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