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.1KB

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