Development of an internal social media platform with personalised dashboards for students
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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. from __future__ import absolute_import
  2. import collections
  3. import logging
  4. import os
  5. import re
  6. from pip._vendor import pkg_resources, six
  7. from pip._vendor.packaging.utils import canonicalize_name
  8. from pip._vendor.pkg_resources import RequirementParseError
  9. from pip._internal.exceptions import 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.deprecation import deprecated
  15. from pip._internal.utils.misc import (
  16. dist_is_editable, get_installed_distributions, make_vcs_requirement_url,
  17. )
  18. logger = logging.getLogger(__name__)
  19. def freeze(
  20. requirement=None,
  21. find_links=None, local_only=None, user_only=None, skip_regex=None,
  22. isolated=False,
  23. wheel_cache=None,
  24. exclude_editable=False,
  25. skip=()):
  26. find_links = find_links or []
  27. skip_match = None
  28. if skip_regex:
  29. skip_match = re.compile(skip_regex).search
  30. dependency_links = []
  31. for dist in pkg_resources.working_set:
  32. if dist.has_metadata('dependency_links.txt'):
  33. dependency_links.extend(
  34. dist.get_metadata_lines('dependency_links.txt')
  35. )
  36. for link in find_links:
  37. if '#egg=' in link:
  38. dependency_links.append(link)
  39. for link in find_links:
  40. yield '-f %s' % link
  41. installations = {}
  42. for dist in get_installed_distributions(local_only=local_only,
  43. skip=(),
  44. user_only=user_only):
  45. try:
  46. req = FrozenRequirement.from_dist(
  47. dist,
  48. dependency_links
  49. )
  50. except RequirementParseError:
  51. logger.warning(
  52. "Could not parse requirement: %s",
  53. dist.project_name
  54. )
  55. continue
  56. if exclude_editable and req.editable:
  57. continue
  58. installations[req.name] = req
  59. if requirement:
  60. # the options that don't get turned into an InstallRequirement
  61. # should only be emitted once, even if the same option is in multiple
  62. # requirements files, so we need to keep track of what has been emitted
  63. # so that we don't emit it again if it's seen again
  64. emitted_options = set()
  65. # keep track of which files a requirement is in so that we can
  66. # give an accurate warning if a requirement appears multiple times.
  67. req_files = collections.defaultdict(list)
  68. for req_file_path in requirement:
  69. with open(req_file_path) as req_file:
  70. for line in req_file:
  71. if (not line.strip() or
  72. line.strip().startswith('#') or
  73. (skip_match and skip_match(line)) or
  74. line.startswith((
  75. '-r', '--requirement',
  76. '-Z', '--always-unzip',
  77. '-f', '--find-links',
  78. '-i', '--index-url',
  79. '--pre',
  80. '--trusted-host',
  81. '--process-dependency-links',
  82. '--extra-index-url'))):
  83. line = line.rstrip()
  84. if line not in emitted_options:
  85. emitted_options.add(line)
  86. yield line
  87. continue
  88. if line.startswith('-e') or line.startswith('--editable'):
  89. if line.startswith('-e'):
  90. line = line[2:].strip()
  91. else:
  92. line = line[len('--editable'):].strip().lstrip('=')
  93. line_req = install_req_from_editable(
  94. line,
  95. isolated=isolated,
  96. wheel_cache=wheel_cache,
  97. )
  98. else:
  99. line_req = install_req_from_line(
  100. COMMENT_RE.sub('', line).strip(),
  101. isolated=isolated,
  102. wheel_cache=wheel_cache,
  103. )
  104. if not line_req.name:
  105. logger.info(
  106. "Skipping line in requirement file [%s] because "
  107. "it's not clear what it would install: %s",
  108. req_file_path, line.strip(),
  109. )
  110. logger.info(
  111. " (add #egg=PackageName to the URL to avoid"
  112. " this warning)"
  113. )
  114. elif line_req.name not in installations:
  115. # either it's not installed, or it is installed
  116. # but has been processed already
  117. if not req_files[line_req.name]:
  118. logger.warning(
  119. "Requirement file [%s] contains %s, but that "
  120. "package is not installed",
  121. req_file_path,
  122. COMMENT_RE.sub('', line).strip(),
  123. )
  124. else:
  125. req_files[line_req.name].append(req_file_path)
  126. else:
  127. yield str(installations[line_req.name]).rstrip()
  128. del installations[line_req.name]
  129. req_files[line_req.name].append(req_file_path)
  130. # Warn about requirements that were included multiple times (in a
  131. # single requirements file or in different requirements files).
  132. for name, files in six.iteritems(req_files):
  133. if len(files) > 1:
  134. logger.warning("Requirement %s included multiple times [%s]",
  135. name, ', '.join(sorted(set(files))))
  136. yield(
  137. '## The following requirements were added by '
  138. 'pip freeze:'
  139. )
  140. for installation in sorted(
  141. installations.values(), key=lambda x: x.name.lower()):
  142. if canonicalize_name(installation.name) not in skip:
  143. yield str(installation).rstrip()
  144. class FrozenRequirement(object):
  145. def __init__(self, name, req, editable, comments=()):
  146. self.name = name
  147. self.req = req
  148. self.editable = editable
  149. self.comments = comments
  150. _rev_re = re.compile(r'-r(\d+)$')
  151. _date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
  152. @classmethod
  153. def _init_args_from_dist(cls, dist, dependency_links):
  154. """
  155. Compute and return arguments (req, editable, comments) to pass to
  156. FrozenRequirement.__init__().
  157. This method is for use in FrozenRequirement.from_dist().
  158. """
  159. location = os.path.normcase(os.path.abspath(dist.location))
  160. comments = []
  161. from pip._internal.vcs import vcs, get_src_requirement
  162. if dist_is_editable(dist) and vcs.get_backend_name(location):
  163. editable = True
  164. try:
  165. req = get_src_requirement(dist, location)
  166. except InstallationError as exc:
  167. logger.warning(
  168. "Error when trying to get requirement for VCS system %s, "
  169. "falling back to uneditable format", exc
  170. )
  171. req = None
  172. if req is None:
  173. logger.warning(
  174. 'Could not determine repository location of %s', location
  175. )
  176. comments.append(
  177. '## !! Could not determine repository location'
  178. )
  179. req = dist.as_requirement()
  180. editable = False
  181. else:
  182. editable = False
  183. req = dist.as_requirement()
  184. specs = req.specs
  185. assert len(specs) == 1 and specs[0][0] in ["==", "==="], \
  186. 'Expected 1 spec with == or ===; specs = %r; dist = %r' % \
  187. (specs, dist)
  188. version = specs[0][1]
  189. ver_match = cls._rev_re.search(version)
  190. date_match = cls._date_re.search(version)
  191. if ver_match or date_match:
  192. svn_backend = vcs.get_backend('svn')
  193. if svn_backend:
  194. svn_location = svn_backend().get_location(
  195. dist,
  196. dependency_links,
  197. )
  198. if not svn_location:
  199. logger.warning(
  200. 'Warning: cannot find svn location for %s', req,
  201. )
  202. comments.append(
  203. '## FIXME: could not find svn URL in dependency_links '
  204. 'for this package:'
  205. )
  206. else:
  207. deprecated(
  208. "SVN editable detection based on dependency links "
  209. "will be dropped in the future.",
  210. replacement=None,
  211. gone_in="18.2",
  212. issue=4187,
  213. )
  214. comments.append(
  215. '# Installing as editable to satisfy requirement %s:' %
  216. req
  217. )
  218. if ver_match:
  219. rev = ver_match.group(1)
  220. else:
  221. rev = '{%s}' % date_match.group(1)
  222. editable = True
  223. egg_name = cls.egg_name(dist)
  224. req = make_vcs_requirement_url(svn_location, rev, egg_name)
  225. return (req, editable, comments)
  226. @classmethod
  227. def from_dist(cls, dist, dependency_links):
  228. args = cls._init_args_from_dist(dist, dependency_links)
  229. return cls(dist.project_name, *args)
  230. @staticmethod
  231. def egg_name(dist):
  232. name = dist.egg_name()
  233. match = re.search(r'-py\d\.\d$', name)
  234. if match:
  235. name = name[:match.start()]
  236. return name
  237. def __str__(self):
  238. req = self.req
  239. if self.editable:
  240. req = '-e %s' % req
  241. return '\n'.join(list(self.comments) + [str(req)]) + '\n'