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.
 
 
 
 

661 lines
27 KiB

  1. from __future__ import absolute_import
  2. from collections import defaultdict
  3. import functools
  4. import itertools
  5. import logging
  6. import os
  7. from pip._vendor import pkg_resources
  8. from pip._vendor import requests
  9. from pip.download import (url_to_path, unpack_url)
  10. from pip.exceptions import (InstallationError, BestVersionAlreadyInstalled,
  11. DistributionNotFound, PreviousBuildDirError)
  12. from pip.req.req_install import InstallRequirement
  13. from pip.utils import (
  14. display_path, dist_in_usersite, ensure_dir, normalize_path)
  15. from pip.utils.logging import indent_log
  16. from pip.vcs import vcs
  17. logger = logging.getLogger(__name__)
  18. class Requirements(object):
  19. def __init__(self):
  20. self._keys = []
  21. self._dict = {}
  22. def keys(self):
  23. return self._keys
  24. def values(self):
  25. return [self._dict[key] for key in self._keys]
  26. def __contains__(self, item):
  27. return item in self._keys
  28. def __setitem__(self, key, value):
  29. if key not in self._keys:
  30. self._keys.append(key)
  31. self._dict[key] = value
  32. def __getitem__(self, key):
  33. return self._dict[key]
  34. def __repr__(self):
  35. values = ['%s: %s' % (repr(k), repr(self[k])) for k in self.keys()]
  36. return 'Requirements({%s})' % ', '.join(values)
  37. class DistAbstraction(object):
  38. """Abstracts out the wheel vs non-wheel prepare_files logic.
  39. The requirements for anything installable are as follows:
  40. - we must be able to determine the requirement name
  41. (or we can't correctly handle the non-upgrade case).
  42. - we must be able to generate a list of run-time dependencies
  43. without installing any additional packages (or we would
  44. have to either burn time by doing temporary isolated installs
  45. or alternatively violate pips 'don't start installing unless
  46. all requirements are available' rule - neither of which are
  47. desirable).
  48. - for packages with setup requirements, we must also be able
  49. to determine their requirements without installing additional
  50. packages (for the same reason as run-time dependencies)
  51. - we must be able to create a Distribution object exposing the
  52. above metadata.
  53. """
  54. def __init__(self, req_to_install):
  55. self.req_to_install = req_to_install
  56. def dist(self, finder):
  57. """Return a setuptools Dist object."""
  58. raise NotImplementedError(self.dist)
  59. def prep_for_dist(self):
  60. """Ensure that we can get a Dist for this requirement."""
  61. raise NotImplementedError(self.dist)
  62. def make_abstract_dist(req_to_install):
  63. """Factory to make an abstract dist object.
  64. Preconditions: Either an editable req with a source_dir, or satisfied_by or
  65. a wheel link, or a non-editable req with a source_dir.
  66. :return: A concrete DistAbstraction.
  67. """
  68. if req_to_install.editable:
  69. return IsSDist(req_to_install)
  70. elif req_to_install.link and req_to_install.link.is_wheel:
  71. return IsWheel(req_to_install)
  72. else:
  73. return IsSDist(req_to_install)
  74. class IsWheel(DistAbstraction):
  75. def dist(self, finder):
  76. return list(pkg_resources.find_distributions(
  77. self.req_to_install.source_dir))[0]
  78. def prep_for_dist(self):
  79. # FIXME:https://github.com/pypa/pip/issues/1112
  80. pass
  81. class IsSDist(DistAbstraction):
  82. def dist(self, finder):
  83. dist = self.req_to_install.get_dist()
  84. # FIXME: shouldn't be globally added:
  85. if dist.has_metadata('dependency_links.txt'):
  86. finder.add_dependency_links(
  87. dist.get_metadata_lines('dependency_links.txt')
  88. )
  89. return dist
  90. def prep_for_dist(self):
  91. self.req_to_install.run_egg_info()
  92. self.req_to_install.assert_source_matches_version()
  93. class Installed(DistAbstraction):
  94. def dist(self, finder):
  95. return self.req_to_install.satisfied_by
  96. def prep_for_dist(self):
  97. pass
  98. class RequirementSet(object):
  99. def __init__(self, build_dir, src_dir, download_dir, upgrade=False,
  100. ignore_installed=False, as_egg=False, target_dir=None,
  101. ignore_dependencies=False, force_reinstall=False,
  102. use_user_site=False, session=None, pycompile=True,
  103. isolated=False, wheel_download_dir=None,
  104. wheel_cache=None):
  105. """Create a RequirementSet.
  106. :param wheel_download_dir: Where still-packed .whl files should be
  107. written to. If None they are written to the download_dir parameter.
  108. Separate to download_dir to permit only keeping wheel archives for
  109. pip wheel.
  110. :param download_dir: Where still packed archives should be written to.
  111. If None they are not saved, and are deleted immediately after
  112. unpacking.
  113. :param wheel_cache: The pip wheel cache, for passing to
  114. InstallRequirement.
  115. """
  116. if session is None:
  117. raise TypeError(
  118. "RequirementSet() missing 1 required keyword argument: "
  119. "'session'"
  120. )
  121. self.build_dir = build_dir
  122. self.src_dir = src_dir
  123. # XXX: download_dir and wheel_download_dir overlap semantically and may
  124. # be combined if we're willing to have non-wheel archives present in
  125. # the wheelhouse output by 'pip wheel'.
  126. self.download_dir = download_dir
  127. self.upgrade = upgrade
  128. self.ignore_installed = ignore_installed
  129. self.force_reinstall = force_reinstall
  130. self.requirements = Requirements()
  131. # Mapping of alias: real_name
  132. self.requirement_aliases = {}
  133. self.unnamed_requirements = []
  134. self.ignore_dependencies = ignore_dependencies
  135. self.successfully_downloaded = []
  136. self.successfully_installed = []
  137. self.reqs_to_cleanup = []
  138. self.as_egg = as_egg
  139. self.use_user_site = use_user_site
  140. self.target_dir = target_dir # set from --target option
  141. self.session = session
  142. self.pycompile = pycompile
  143. self.isolated = isolated
  144. if wheel_download_dir:
  145. wheel_download_dir = normalize_path(wheel_download_dir)
  146. self.wheel_download_dir = wheel_download_dir
  147. self._wheel_cache = wheel_cache
  148. # Maps from install_req -> dependencies_of_install_req
  149. self._dependencies = defaultdict(list)
  150. def __str__(self):
  151. reqs = [req for req in self.requirements.values()
  152. if not req.comes_from]
  153. reqs.sort(key=lambda req: req.name.lower())
  154. return ' '.join([str(req.req) for req in reqs])
  155. def __repr__(self):
  156. reqs = [req for req in self.requirements.values()]
  157. reqs.sort(key=lambda req: req.name.lower())
  158. reqs_str = ', '.join([str(req.req) for req in reqs])
  159. return ('<%s object; %d requirement(s): %s>'
  160. % (self.__class__.__name__, len(reqs), reqs_str))
  161. def add_requirement(self, install_req, parent_req_name=None):
  162. """Add install_req as a requirement to install.
  163. :param parent_req_name: The name of the requirement that needed this
  164. added. The name is used because when multiple unnamed requirements
  165. resolve to the same name, we could otherwise end up with dependency
  166. links that point outside the Requirements set. parent_req must
  167. already be added. Note that None implies that this is a user
  168. supplied requirement, vs an inferred one.
  169. :return: Additional requirements to scan. That is either [] if
  170. the requirement is not applicable, or [install_req] if the
  171. requirement is applicable and has just been added.
  172. """
  173. name = install_req.name
  174. if not install_req.match_markers():
  175. logger.warning("Ignoring %s: markers %r don't match your "
  176. "environment", install_req.name,
  177. install_req.markers)
  178. return []
  179. install_req.as_egg = self.as_egg
  180. install_req.use_user_site = self.use_user_site
  181. install_req.target_dir = self.target_dir
  182. install_req.pycompile = self.pycompile
  183. if not name:
  184. # url or path requirement w/o an egg fragment
  185. self.unnamed_requirements.append(install_req)
  186. return [install_req]
  187. else:
  188. try:
  189. existing_req = self.get_requirement(name)
  190. except KeyError:
  191. existing_req = None
  192. if (parent_req_name is None and existing_req and not
  193. existing_req.constraint):
  194. raise InstallationError(
  195. 'Double requirement given: %s (already in %s, name=%r)'
  196. % (install_req, existing_req, name))
  197. if not existing_req:
  198. # Add requirement
  199. self.requirements[name] = install_req
  200. # FIXME: what about other normalizations? E.g., _ vs. -?
  201. if name.lower() != name:
  202. self.requirement_aliases[name.lower()] = name
  203. result = [install_req]
  204. else:
  205. if not existing_req.constraint:
  206. # No need to scan, we've already encountered this for
  207. # scanning.
  208. result = []
  209. elif not install_req.constraint:
  210. # If we're now installing a constraint, mark the existing
  211. # object for real installation.
  212. existing_req.constraint = False
  213. # And now we need to scan this.
  214. result = [existing_req]
  215. # Canonicalise to the already-added object for the backref
  216. # check below.
  217. install_req = existing_req
  218. if parent_req_name:
  219. parent_req = self.get_requirement(parent_req_name)
  220. self._dependencies[parent_req].append(install_req)
  221. return result
  222. def has_requirement(self, project_name):
  223. for name in project_name, project_name.lower():
  224. if name in self.requirements or name in self.requirement_aliases:
  225. return True
  226. return False
  227. @property
  228. def has_requirements(self):
  229. return list(req for req in self.requirements.values() if not
  230. req.constraint) or self.unnamed_requirements
  231. @property
  232. def is_download(self):
  233. if self.download_dir:
  234. self.download_dir = os.path.expanduser(self.download_dir)
  235. if os.path.exists(self.download_dir):
  236. return True
  237. else:
  238. logger.critical('Could not find download directory')
  239. raise InstallationError(
  240. "Could not find or access download directory '%s'"
  241. % display_path(self.download_dir))
  242. return False
  243. def get_requirement(self, project_name):
  244. for name in project_name, project_name.lower():
  245. if name in self.requirements:
  246. return self.requirements[name]
  247. if name in self.requirement_aliases:
  248. return self.requirements[self.requirement_aliases[name]]
  249. raise KeyError("No project with the name %r" % project_name)
  250. def uninstall(self, auto_confirm=False):
  251. for req in self.requirements.values():
  252. if req.constraint:
  253. continue
  254. req.uninstall(auto_confirm=auto_confirm)
  255. req.commit_uninstall()
  256. def _walk_req_to_install(self, handler):
  257. """Call handler for all pending reqs.
  258. :param handler: Handle a single requirement. Should take a requirement
  259. to install. Can optionally return an iterable of additional
  260. InstallRequirements to cover.
  261. """
  262. # The list() here is to avoid potential mutate-while-iterating bugs.
  263. discovered_reqs = []
  264. reqs = itertools.chain(
  265. list(self.unnamed_requirements), list(self.requirements.values()),
  266. discovered_reqs)
  267. for req_to_install in reqs:
  268. more_reqs = handler(req_to_install)
  269. if more_reqs:
  270. discovered_reqs.extend(more_reqs)
  271. def prepare_files(self, finder):
  272. """
  273. Prepare process. Create temp directories, download and/or unpack files.
  274. """
  275. # make the wheelhouse
  276. if self.wheel_download_dir:
  277. ensure_dir(self.wheel_download_dir)
  278. self._walk_req_to_install(
  279. functools.partial(self._prepare_file, finder))
  280. def _check_skip_installed(self, req_to_install, finder):
  281. """Check if req_to_install should be skipped.
  282. This will check if the req is installed, and whether we should upgrade
  283. or reinstall it, taking into account all the relevant user options.
  284. After calling this req_to_install will only have satisfied_by set to
  285. None if the req_to_install is to be upgraded/reinstalled etc. Any
  286. other value will be a dist recording the current thing installed that
  287. satisfies the requirement.
  288. Note that for vcs urls and the like we can't assess skipping in this
  289. routine - we simply identify that we need to pull the thing down,
  290. then later on it is pulled down and introspected to assess upgrade/
  291. reinstalls etc.
  292. :return: A text reason for why it was skipped, or None.
  293. """
  294. # Check whether to upgrade/reinstall this req or not.
  295. req_to_install.check_if_exists()
  296. if req_to_install.satisfied_by:
  297. skip_reason = 'satisfied (use --upgrade to upgrade)'
  298. if self.upgrade:
  299. best_installed = False
  300. # For link based requirements we have to pull the
  301. # tree down and inspect to assess the version #, so
  302. # its handled way down.
  303. if not (self.force_reinstall or req_to_install.link):
  304. try:
  305. finder.find_requirement(req_to_install, self.upgrade)
  306. except BestVersionAlreadyInstalled:
  307. skip_reason = 'up-to-date'
  308. best_installed = True
  309. except DistributionNotFound:
  310. # No distribution found, so we squash the
  311. # error - it will be raised later when we
  312. # re-try later to do the install.
  313. # Why don't we just raise here?
  314. pass
  315. if not best_installed:
  316. # don't uninstall conflict if user install and
  317. # conflict is not user install
  318. if not (self.use_user_site and not
  319. dist_in_usersite(req_to_install.satisfied_by)):
  320. req_to_install.conflicts_with = \
  321. req_to_install.satisfied_by
  322. req_to_install.satisfied_by = None
  323. return skip_reason
  324. else:
  325. return None
  326. def _prepare_file(self, finder, req_to_install):
  327. """Prepare a single requirements files.
  328. :return: A list of addition InstallRequirements to also install.
  329. """
  330. # Tell user what we are doing for this requirement:
  331. # obtain (editable), skipping, processing (local url), collecting
  332. # (remote url or package name)
  333. if req_to_install.constraint or req_to_install.prepared:
  334. return []
  335. req_to_install.prepared = True
  336. if req_to_install.editable:
  337. logger.info('Obtaining %s', req_to_install)
  338. else:
  339. # satisfied_by is only evaluated by calling _check_skip_installed,
  340. # so it must be None here.
  341. assert req_to_install.satisfied_by is None
  342. if not self.ignore_installed:
  343. skip_reason = self._check_skip_installed(
  344. req_to_install, finder)
  345. if req_to_install.satisfied_by:
  346. assert skip_reason is not None, (
  347. '_check_skip_installed returned None but '
  348. 'req_to_install.satisfied_by is set to %r'
  349. % (req_to_install.satisfied_by,))
  350. logger.info(
  351. 'Requirement already %s: %s', skip_reason,
  352. req_to_install)
  353. else:
  354. if (req_to_install.link and
  355. req_to_install.link.scheme == 'file'):
  356. path = url_to_path(req_to_install.link.url)
  357. logger.info('Processing %s', display_path(path))
  358. else:
  359. logger.info('Collecting %s', req_to_install)
  360. with indent_log():
  361. # ################################ #
  362. # # vcs update or unpack archive # #
  363. # ################################ #
  364. if req_to_install.editable:
  365. req_to_install.ensure_has_source_dir(self.src_dir)
  366. req_to_install.update_editable(not self.is_download)
  367. abstract_dist = make_abstract_dist(req_to_install)
  368. abstract_dist.prep_for_dist()
  369. if self.is_download:
  370. req_to_install.archive(self.download_dir)
  371. elif req_to_install.satisfied_by:
  372. abstract_dist = Installed(req_to_install)
  373. else:
  374. # @@ if filesystem packages are not marked
  375. # editable in a req, a non deterministic error
  376. # occurs when the script attempts to unpack the
  377. # build directory
  378. req_to_install.ensure_has_source_dir(self.build_dir)
  379. # If a checkout exists, it's unwise to keep going. version
  380. # inconsistencies are logged later, but do not fail the
  381. # installation.
  382. # FIXME: this won't upgrade when there's an existing
  383. # package unpacked in `req_to_install.source_dir`
  384. if os.path.exists(
  385. os.path.join(req_to_install.source_dir, 'setup.py')):
  386. raise PreviousBuildDirError(
  387. "pip can't proceed with requirements '%s' due to a"
  388. " pre-existing build directory (%s). This is "
  389. "likely due to a previous installation that failed"
  390. ". pip is being responsible and not assuming it "
  391. "can delete this. Please delete it and try again."
  392. % (req_to_install, req_to_install.source_dir)
  393. )
  394. req_to_install.populate_link(finder, self.upgrade)
  395. # We can't hit this spot and have populate_link return None.
  396. # req_to_install.satisfied_by is None here (because we're
  397. # guarded) and upgrade has no impact except when satisfied_by
  398. # is not None.
  399. # Then inside find_requirement existing_applicable -> False
  400. # If no new versions are found, DistributionNotFound is raised,
  401. # otherwise a result is guaranteed.
  402. assert req_to_install.link
  403. try:
  404. download_dir = self.download_dir
  405. # We always delete unpacked sdists after pip ran.
  406. autodelete_unpacked = True
  407. if req_to_install.link.is_wheel \
  408. and self.wheel_download_dir:
  409. # when doing 'pip wheel` we download wheels to a
  410. # dedicated dir.
  411. download_dir = self.wheel_download_dir
  412. if req_to_install.link.is_wheel:
  413. if download_dir:
  414. # When downloading, we only unpack wheels to get
  415. # metadata.
  416. autodelete_unpacked = True
  417. else:
  418. # When installing a wheel, we use the unpacked
  419. # wheel.
  420. autodelete_unpacked = False
  421. unpack_url(
  422. req_to_install.link, req_to_install.source_dir,
  423. download_dir, autodelete_unpacked,
  424. session=self.session)
  425. except requests.HTTPError as exc:
  426. logger.critical(
  427. 'Could not install requirement %s because '
  428. 'of error %s',
  429. req_to_install,
  430. exc,
  431. )
  432. raise InstallationError(
  433. 'Could not install requirement %s because '
  434. 'of HTTP error %s for URL %s' %
  435. (req_to_install, exc, req_to_install.link)
  436. )
  437. abstract_dist = make_abstract_dist(req_to_install)
  438. abstract_dist.prep_for_dist()
  439. if self.is_download:
  440. # Make a .zip of the source_dir we already created.
  441. if req_to_install.link.scheme in vcs.all_schemes:
  442. req_to_install.archive(self.download_dir)
  443. # req_to_install.req is only avail after unpack for URL
  444. # pkgs repeat check_if_exists to uninstall-on-upgrade
  445. # (#14)
  446. if not self.ignore_installed:
  447. req_to_install.check_if_exists()
  448. if req_to_install.satisfied_by:
  449. if self.upgrade or self.ignore_installed:
  450. # don't uninstall conflict if user install and
  451. # conflict is not user install
  452. if not (self.use_user_site and not
  453. dist_in_usersite(
  454. req_to_install.satisfied_by)):
  455. req_to_install.conflicts_with = \
  456. req_to_install.satisfied_by
  457. req_to_install.satisfied_by = None
  458. else:
  459. logger.info(
  460. 'Requirement already satisfied (use '
  461. '--upgrade to upgrade): %s',
  462. req_to_install,
  463. )
  464. # ###################### #
  465. # # parse dependencies # #
  466. # ###################### #
  467. dist = abstract_dist.dist(finder)
  468. more_reqs = []
  469. def add_req(subreq):
  470. sub_install_req = InstallRequirement(
  471. str(subreq),
  472. req_to_install,
  473. isolated=self.isolated,
  474. wheel_cache=self._wheel_cache,
  475. )
  476. more_reqs.extend(self.add_requirement(
  477. sub_install_req, req_to_install.name))
  478. # We add req_to_install before its dependencies, so that we
  479. # can refer to it when adding dependencies.
  480. if not self.has_requirement(req_to_install.name):
  481. # 'unnamed' requirements will get added here
  482. self.add_requirement(req_to_install, None)
  483. if not self.ignore_dependencies:
  484. if (req_to_install.extras):
  485. logger.debug(
  486. "Installing extra requirements: %r",
  487. ','.join(req_to_install.extras),
  488. )
  489. missing_requested = sorted(
  490. set(req_to_install.extras) - set(dist.extras)
  491. )
  492. for missing in missing_requested:
  493. logger.warning(
  494. '%s does not provide the extra \'%s\'',
  495. dist, missing
  496. )
  497. available_requested = sorted(
  498. set(dist.extras) & set(req_to_install.extras)
  499. )
  500. for subreq in dist.requires(available_requested):
  501. add_req(subreq)
  502. # cleanup tmp src
  503. self.reqs_to_cleanup.append(req_to_install)
  504. if not req_to_install.editable and not req_to_install.satisfied_by:
  505. # XXX: --no-install leads this to report 'Successfully
  506. # downloaded' for only non-editable reqs, even though we took
  507. # action on them.
  508. self.successfully_downloaded.append(req_to_install)
  509. return more_reqs
  510. def cleanup_files(self):
  511. """Clean up files, remove builds."""
  512. logger.debug('Cleaning up...')
  513. with indent_log():
  514. for req in self.reqs_to_cleanup:
  515. req.remove_temporary_source()
  516. def _to_install(self):
  517. """Create the installation order.
  518. The installation order is topological - requirements are installed
  519. before the requiring thing. We break cycles at an arbitrary point,
  520. and make no other guarantees.
  521. """
  522. # The current implementation, which we may change at any point
  523. # installs the user specified things in the order given, except when
  524. # dependencies must come earlier to achieve topological order.
  525. order = []
  526. ordered_reqs = set()
  527. def schedule(req):
  528. if req.satisfied_by or req in ordered_reqs:
  529. return
  530. if req.constraint:
  531. return
  532. ordered_reqs.add(req)
  533. for dep in self._dependencies[req]:
  534. schedule(dep)
  535. order.append(req)
  536. for install_req in self.requirements.values():
  537. schedule(install_req)
  538. return order
  539. def install(self, install_options, global_options=(), *args, **kwargs):
  540. """
  541. Install everything in this set (after having downloaded and unpacked
  542. the packages)
  543. """
  544. to_install = self._to_install()
  545. if to_install:
  546. logger.info(
  547. 'Installing collected packages: %s',
  548. ', '.join([req.name for req in to_install]),
  549. )
  550. with indent_log():
  551. for requirement in to_install:
  552. if requirement.conflicts_with:
  553. logger.info(
  554. 'Found existing installation: %s',
  555. requirement.conflicts_with,
  556. )
  557. with indent_log():
  558. requirement.uninstall(auto_confirm=True)
  559. try:
  560. requirement.install(
  561. install_options,
  562. global_options,
  563. *args,
  564. **kwargs
  565. )
  566. except:
  567. # if install did not succeed, rollback previous uninstall
  568. if (requirement.conflicts_with and not
  569. requirement.install_succeeded):
  570. requirement.rollback_uninstall()
  571. raise
  572. else:
  573. if (requirement.conflicts_with and
  574. requirement.install_succeeded):
  575. requirement.commit_uninstall()
  576. requirement.remove_temporary_source()
  577. self.successfully_installed = to_install