You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

freeze.py 9.6KB

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