freeze.py 10 KB

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