req_install.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. from __future__ import absolute_import
  2. import logging
  3. import os
  4. import re
  5. import shutil
  6. import sys
  7. import tempfile
  8. import traceback
  9. import warnings
  10. import zipfile
  11. from distutils import sysconfig
  12. from distutils.util import change_root
  13. from email.parser import FeedParser
  14. from pip._vendor import pkg_resources, six
  15. from pip._vendor.packaging import specifiers
  16. from pip._vendor.packaging.markers import Marker
  17. from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
  18. from pip._vendor.packaging.utils import canonicalize_name
  19. from pip._vendor.packaging.version import Version, parse as parse_version
  20. from pip._vendor.six.moves import configparser
  21. import pip.wheel
  22. from pip.compat import native_str, get_stdlib, WINDOWS
  23. from pip.download import is_url, url_to_path, path_to_url, is_archive_file
  24. from pip.exceptions import (
  25. InstallationError, UninstallationError,
  26. )
  27. from pip.locations import (
  28. bin_py, running_under_virtualenv, PIP_DELETE_MARKER_FILENAME, bin_user,
  29. )
  30. from pip.utils import (
  31. display_path, rmtree, ask_path_exists, backup_dir, is_installable_dir,
  32. dist_in_usersite, dist_in_site_packages, egg_link_path,
  33. call_subprocess, read_text_file, FakeFile, _make_build_dir, ensure_dir,
  34. get_installed_version, normalize_path, dist_is_local,
  35. )
  36. from pip.utils.hashes import Hashes
  37. from pip.utils.deprecation import RemovedInPip10Warning
  38. from pip.utils.logging import indent_log
  39. from pip.utils.setuptools_build import SETUPTOOLS_SHIM
  40. from pip.utils.ui import open_spinner
  41. from pip.req.req_uninstall import UninstallPathSet
  42. from pip.vcs import vcs
  43. from pip.wheel import move_wheel_files, Wheel
  44. logger = logging.getLogger(__name__)
  45. operators = specifiers.Specifier._operators.keys()
  46. def _strip_extras(path):
  47. m = re.match(r'^(.+)(\[[^\]]+\])$', path)
  48. extras = None
  49. if m:
  50. path_no_extras = m.group(1)
  51. extras = m.group(2)
  52. else:
  53. path_no_extras = path
  54. return path_no_extras, extras
  55. def _safe_extras(extras):
  56. return set(pkg_resources.safe_extra(extra) for extra in extras)
  57. class InstallRequirement(object):
  58. def __init__(self, req, comes_from, source_dir=None, editable=False,
  59. link=None, as_egg=False, update=True,
  60. pycompile=True, markers=None, isolated=False, options=None,
  61. wheel_cache=None, constraint=False):
  62. self.extras = ()
  63. if isinstance(req, six.string_types):
  64. try:
  65. req = Requirement(req)
  66. except InvalidRequirement:
  67. if os.path.sep in req:
  68. add_msg = "It looks like a path. Does it exist ?"
  69. elif '=' in req and not any(op in req for op in operators):
  70. add_msg = "= is not a valid operator. Did you mean == ?"
  71. else:
  72. add_msg = traceback.format_exc()
  73. raise InstallationError(
  74. "Invalid requirement: '%s'\n%s" % (req, add_msg))
  75. self.extras = _safe_extras(req.extras)
  76. self.req = req
  77. self.comes_from = comes_from
  78. self.constraint = constraint
  79. self.source_dir = source_dir
  80. self.editable = editable
  81. self._wheel_cache = wheel_cache
  82. self.link = self.original_link = link
  83. self.as_egg = as_egg
  84. if markers is not None:
  85. self.markers = markers
  86. else:
  87. self.markers = req and req.marker
  88. self._egg_info_path = None
  89. # This holds the pkg_resources.Distribution object if this requirement
  90. # is already available:
  91. self.satisfied_by = None
  92. # This hold the pkg_resources.Distribution object if this requirement
  93. # conflicts with another installed distribution:
  94. self.conflicts_with = None
  95. # Temporary build location
  96. self._temp_build_dir = None
  97. # Used to store the global directory where the _temp_build_dir should
  98. # have been created. Cf _correct_build_location method.
  99. self._ideal_build_dir = None
  100. # True if the editable should be updated:
  101. self.update = update
  102. # Set to True after successful installation
  103. self.install_succeeded = None
  104. # UninstallPathSet of uninstalled distribution (for possible rollback)
  105. self.uninstalled = None
  106. # Set True if a legitimate do-nothing-on-uninstall has happened - e.g.
  107. # system site packages, stdlib packages.
  108. self.nothing_to_uninstall = False
  109. self.use_user_site = False
  110. self.target_dir = None
  111. self.options = options if options else {}
  112. self.pycompile = pycompile
  113. # Set to True after successful preparation of this requirement
  114. self.prepared = False
  115. self.isolated = isolated
  116. @classmethod
  117. def from_editable(cls, editable_req, comes_from=None, default_vcs=None,
  118. isolated=False, options=None, wheel_cache=None,
  119. constraint=False):
  120. from pip.index import Link
  121. name, url, extras_override = parse_editable(
  122. editable_req, default_vcs)
  123. if url.startswith('file:'):
  124. source_dir = url_to_path(url)
  125. else:
  126. source_dir = None
  127. res = cls(name, comes_from, source_dir=source_dir,
  128. editable=True,
  129. link=Link(url),
  130. constraint=constraint,
  131. isolated=isolated,
  132. options=options if options else {},
  133. wheel_cache=wheel_cache)
  134. if extras_override is not None:
  135. res.extras = _safe_extras(extras_override)
  136. return res
  137. @classmethod
  138. def from_line(
  139. cls, name, comes_from=None, isolated=False, options=None,
  140. wheel_cache=None, constraint=False):
  141. """Creates an InstallRequirement from a name, which might be a
  142. requirement, directory containing 'setup.py', filename, or URL.
  143. """
  144. from pip.index import Link
  145. if is_url(name):
  146. marker_sep = '; '
  147. else:
  148. marker_sep = ';'
  149. if marker_sep in name:
  150. name, markers = name.split(marker_sep, 1)
  151. markers = markers.strip()
  152. if not markers:
  153. markers = None
  154. else:
  155. markers = Marker(markers)
  156. else:
  157. markers = None
  158. name = name.strip()
  159. req = None
  160. path = os.path.normpath(os.path.abspath(name))
  161. link = None
  162. extras = None
  163. if is_url(name):
  164. link = Link(name)
  165. else:
  166. p, extras = _strip_extras(path)
  167. if (os.path.isdir(p) and
  168. (os.path.sep in name or name.startswith('.'))):
  169. if not is_installable_dir(p):
  170. raise InstallationError(
  171. "Directory %r is not installable. File 'setup.py' "
  172. "not found." % name
  173. )
  174. link = Link(path_to_url(p))
  175. elif is_archive_file(p):
  176. if not os.path.isfile(p):
  177. logger.warning(
  178. 'Requirement %r looks like a filename, but the '
  179. 'file does not exist',
  180. name
  181. )
  182. link = Link(path_to_url(p))
  183. # it's a local file, dir, or url
  184. if link:
  185. # Handle relative file URLs
  186. if link.scheme == 'file' and re.search(r'\.\./', link.url):
  187. link = Link(
  188. path_to_url(os.path.normpath(os.path.abspath(link.path))))
  189. # wheel file
  190. if link.is_wheel:
  191. wheel = Wheel(link.filename) # can raise InvalidWheelFilename
  192. req = "%s==%s" % (wheel.name, wheel.version)
  193. else:
  194. # set the req to the egg fragment. when it's not there, this
  195. # will become an 'unnamed' requirement
  196. req = link.egg_fragment
  197. # a requirement specifier
  198. else:
  199. req = name
  200. options = options if options else {}
  201. res = cls(req, comes_from, link=link, markers=markers,
  202. isolated=isolated, options=options,
  203. wheel_cache=wheel_cache, constraint=constraint)
  204. if extras:
  205. res.extras = _safe_extras(
  206. Requirement('placeholder' + extras).extras)
  207. return res
  208. def __str__(self):
  209. if self.req:
  210. s = str(self.req)
  211. if self.link:
  212. s += ' from %s' % self.link.url
  213. else:
  214. s = self.link.url if self.link else None
  215. if self.satisfied_by is not None:
  216. s += ' in %s' % display_path(self.satisfied_by.location)
  217. if self.comes_from:
  218. if isinstance(self.comes_from, six.string_types):
  219. comes_from = self.comes_from
  220. else:
  221. comes_from = self.comes_from.from_path()
  222. if comes_from:
  223. s += ' (from %s)' % comes_from
  224. return s
  225. def __repr__(self):
  226. return '<%s object: %s editable=%r>' % (
  227. self.__class__.__name__, str(self), self.editable)
  228. def populate_link(self, finder, upgrade, require_hashes):
  229. """Ensure that if a link can be found for this, that it is found.
  230. Note that self.link may still be None - if Upgrade is False and the
  231. requirement is already installed.
  232. If require_hashes is True, don't use the wheel cache, because cached
  233. wheels, always built locally, have different hashes than the files
  234. downloaded from the index server and thus throw false hash mismatches.
  235. Furthermore, cached wheels at present have undeterministic contents due
  236. to file modification times.
  237. """
  238. if self.link is None:
  239. self.link = finder.find_requirement(self, upgrade)
  240. if self._wheel_cache is not None and not require_hashes:
  241. old_link = self.link
  242. self.link = self._wheel_cache.cached_wheel(self.link, self.name)
  243. if old_link != self.link:
  244. logger.debug('Using cached wheel link: %s', self.link)
  245. @property
  246. def specifier(self):
  247. return self.req.specifier
  248. @property
  249. def is_pinned(self):
  250. """Return whether I am pinned to an exact version.
  251. For example, some-package==1.2 is pinned; some-package>1.2 is not.
  252. """
  253. specifiers = self.specifier
  254. return (len(specifiers) == 1 and
  255. next(iter(specifiers)).operator in ('==', '==='))
  256. def from_path(self):
  257. if self.req is None:
  258. return None
  259. s = str(self.req)
  260. if self.comes_from:
  261. if isinstance(self.comes_from, six.string_types):
  262. comes_from = self.comes_from
  263. else:
  264. comes_from = self.comes_from.from_path()
  265. if comes_from:
  266. s += '->' + comes_from
  267. return s
  268. def build_location(self, build_dir):
  269. if self._temp_build_dir is not None:
  270. return self._temp_build_dir
  271. if self.req is None:
  272. # for requirement via a path to a directory: the name of the
  273. # package is not available yet so we create a temp directory
  274. # Once run_egg_info will have run, we'll be able
  275. # to fix it via _correct_build_location
  276. # Some systems have /tmp as a symlink which confuses custom
  277. # builds (such as numpy). Thus, we ensure that the real path
  278. # is returned.
  279. self._temp_build_dir = os.path.realpath(
  280. tempfile.mkdtemp('-build', 'pip-')
  281. )
  282. self._ideal_build_dir = build_dir
  283. return self._temp_build_dir
  284. if self.editable:
  285. name = self.name.lower()
  286. else:
  287. name = self.name
  288. # FIXME: Is there a better place to create the build_dir? (hg and bzr
  289. # need this)
  290. if not os.path.exists(build_dir):
  291. logger.debug('Creating directory %s', build_dir)
  292. _make_build_dir(build_dir)
  293. return os.path.join(build_dir, name)
  294. def _correct_build_location(self):
  295. """Move self._temp_build_dir to self._ideal_build_dir/self.req.name
  296. For some requirements (e.g. a path to a directory), the name of the
  297. package is not available until we run egg_info, so the build_location
  298. will return a temporary directory and store the _ideal_build_dir.
  299. This is only called by self.egg_info_path to fix the temporary build
  300. directory.
  301. """
  302. if self.source_dir is not None:
  303. return
  304. assert self.req is not None
  305. assert self._temp_build_dir
  306. assert self._ideal_build_dir
  307. old_location = self._temp_build_dir
  308. self._temp_build_dir = None
  309. new_location = self.build_location(self._ideal_build_dir)
  310. if os.path.exists(new_location):
  311. raise InstallationError(
  312. 'A package already exists in %s; please remove it to continue'
  313. % display_path(new_location))
  314. logger.debug(
  315. 'Moving package %s from %s to new location %s',
  316. self, display_path(old_location), display_path(new_location),
  317. )
  318. shutil.move(old_location, new_location)
  319. self._temp_build_dir = new_location
  320. self._ideal_build_dir = None
  321. self.source_dir = new_location
  322. self._egg_info_path = None
  323. @property
  324. def name(self):
  325. if self.req is None:
  326. return None
  327. return native_str(pkg_resources.safe_name(self.req.name))
  328. @property
  329. def setup_py_dir(self):
  330. return os.path.join(
  331. self.source_dir,
  332. self.link and self.link.subdirectory_fragment or '')
  333. @property
  334. def setup_py(self):
  335. assert self.source_dir, "No source dir for %s" % self
  336. try:
  337. import setuptools # noqa
  338. except ImportError:
  339. if get_installed_version('setuptools') is None:
  340. add_msg = "Please install setuptools."
  341. else:
  342. add_msg = traceback.format_exc()
  343. # Setuptools is not available
  344. raise InstallationError(
  345. "Could not import setuptools which is required to "
  346. "install from a source distribution.\n%s" % add_msg
  347. )
  348. setup_py = os.path.join(self.setup_py_dir, 'setup.py')
  349. # Python2 __file__ should not be unicode
  350. if six.PY2 and isinstance(setup_py, six.text_type):
  351. setup_py = setup_py.encode(sys.getfilesystemencoding())
  352. return setup_py
  353. def run_egg_info(self):
  354. assert self.source_dir
  355. if self.name:
  356. logger.debug(
  357. 'Running setup.py (path:%s) egg_info for package %s',
  358. self.setup_py, self.name,
  359. )
  360. else:
  361. logger.debug(
  362. 'Running setup.py (path:%s) egg_info for package from %s',
  363. self.setup_py, self.link,
  364. )
  365. with indent_log():
  366. script = SETUPTOOLS_SHIM % self.setup_py
  367. base_cmd = [sys.executable, '-c', script]
  368. if self.isolated:
  369. base_cmd += ["--no-user-cfg"]
  370. egg_info_cmd = base_cmd + ['egg_info']
  371. # We can't put the .egg-info files at the root, because then the
  372. # source code will be mistaken for an installed egg, causing
  373. # problems
  374. if self.editable:
  375. egg_base_option = []
  376. else:
  377. egg_info_dir = os.path.join(self.setup_py_dir, 'pip-egg-info')
  378. ensure_dir(egg_info_dir)
  379. egg_base_option = ['--egg-base', 'pip-egg-info']
  380. call_subprocess(
  381. egg_info_cmd + egg_base_option,
  382. cwd=self.setup_py_dir,
  383. show_stdout=False,
  384. command_desc='python setup.py egg_info')
  385. if not self.req:
  386. if isinstance(parse_version(self.pkg_info()["Version"]), Version):
  387. op = "=="
  388. else:
  389. op = "==="
  390. self.req = Requirement(
  391. "".join([
  392. self.pkg_info()["Name"],
  393. op,
  394. self.pkg_info()["Version"],
  395. ])
  396. )
  397. self._correct_build_location()
  398. else:
  399. metadata_name = canonicalize_name(self.pkg_info()["Name"])
  400. if canonicalize_name(self.req.name) != metadata_name:
  401. logger.warning(
  402. 'Running setup.py (path:%s) egg_info for package %s '
  403. 'produced metadata for project name %s. Fix your '
  404. '#egg=%s fragments.',
  405. self.setup_py, self.name, metadata_name, self.name
  406. )
  407. self.req = Requirement(metadata_name)
  408. def egg_info_data(self, filename):
  409. if self.satisfied_by is not None:
  410. if not self.satisfied_by.has_metadata(filename):
  411. return None
  412. return self.satisfied_by.get_metadata(filename)
  413. assert self.source_dir
  414. filename = self.egg_info_path(filename)
  415. if not os.path.exists(filename):
  416. return None
  417. data = read_text_file(filename)
  418. return data
  419. def egg_info_path(self, filename):
  420. if self._egg_info_path is None:
  421. if self.editable:
  422. base = self.source_dir
  423. else:
  424. base = os.path.join(self.setup_py_dir, 'pip-egg-info')
  425. filenames = os.listdir(base)
  426. if self.editable:
  427. filenames = []
  428. for root, dirs, files in os.walk(base):
  429. for dir in vcs.dirnames:
  430. if dir in dirs:
  431. dirs.remove(dir)
  432. # Iterate over a copy of ``dirs``, since mutating
  433. # a list while iterating over it can cause trouble.
  434. # (See https://github.com/pypa/pip/pull/462.)
  435. for dir in list(dirs):
  436. # Don't search in anything that looks like a virtualenv
  437. # environment
  438. if (
  439. os.path.lexists(
  440. os.path.join(root, dir, 'bin', 'python')
  441. ) or
  442. os.path.exists(
  443. os.path.join(
  444. root, dir, 'Scripts', 'Python.exe'
  445. )
  446. )):
  447. dirs.remove(dir)
  448. # Also don't search through tests
  449. elif dir == 'test' or dir == 'tests':
  450. dirs.remove(dir)
  451. filenames.extend([os.path.join(root, dir)
  452. for dir in dirs])
  453. filenames = [f for f in filenames if f.endswith('.egg-info')]
  454. if not filenames:
  455. raise InstallationError(
  456. 'No files/directories in %s (from %s)' % (base, filename)
  457. )
  458. assert filenames, \
  459. "No files/directories in %s (from %s)" % (base, filename)
  460. # if we have more than one match, we pick the toplevel one. This
  461. # can easily be the case if there is a dist folder which contains
  462. # an extracted tarball for testing purposes.
  463. if len(filenames) > 1:
  464. filenames.sort(
  465. key=lambda x: x.count(os.path.sep) +
  466. (os.path.altsep and x.count(os.path.altsep) or 0)
  467. )
  468. self._egg_info_path = os.path.join(base, filenames[0])
  469. return os.path.join(self._egg_info_path, filename)
  470. def pkg_info(self):
  471. p = FeedParser()
  472. data = self.egg_info_data('PKG-INFO')
  473. if not data:
  474. logger.warning(
  475. 'No PKG-INFO file found in %s',
  476. display_path(self.egg_info_path('PKG-INFO')),
  477. )
  478. p.feed(data or '')
  479. return p.close()
  480. _requirements_section_re = re.compile(r'\[(.*?)\]')
  481. @property
  482. def installed_version(self):
  483. return get_installed_version(self.name)
  484. def assert_source_matches_version(self):
  485. assert self.source_dir
  486. version = self.pkg_info()['version']
  487. if self.req.specifier and version not in self.req.specifier:
  488. logger.warning(
  489. 'Requested %s, but installing version %s',
  490. self,
  491. self.installed_version,
  492. )
  493. else:
  494. logger.debug(
  495. 'Source in %s has version %s, which satisfies requirement %s',
  496. display_path(self.source_dir),
  497. version,
  498. self,
  499. )
  500. def update_editable(self, obtain=True):
  501. if not self.link:
  502. logger.debug(
  503. "Cannot update repository at %s; repository location is "
  504. "unknown",
  505. self.source_dir,
  506. )
  507. return
  508. assert self.editable
  509. assert self.source_dir
  510. if self.link.scheme == 'file':
  511. # Static paths don't get updated
  512. return
  513. assert '+' in self.link.url, "bad url: %r" % self.link.url
  514. if not self.update:
  515. return
  516. vc_type, url = self.link.url.split('+', 1)
  517. backend = vcs.get_backend(vc_type)
  518. if backend:
  519. vcs_backend = backend(self.link.url)
  520. if obtain:
  521. vcs_backend.obtain(self.source_dir)
  522. else:
  523. vcs_backend.export(self.source_dir)
  524. else:
  525. assert 0, (
  526. 'Unexpected version control type (in %s): %s'
  527. % (self.link, vc_type))
  528. def uninstall(self, auto_confirm=False):
  529. """
  530. Uninstall the distribution currently satisfying this requirement.
  531. Prompts before removing or modifying files unless
  532. ``auto_confirm`` is True.
  533. Refuses to delete or modify files outside of ``sys.prefix`` -
  534. thus uninstallation within a virtual environment can only
  535. modify that virtual environment, even if the virtualenv is
  536. linked to global site-packages.
  537. """
  538. if not self.check_if_exists():
  539. raise UninstallationError(
  540. "Cannot uninstall requirement %s, not installed" % (self.name,)
  541. )
  542. dist = self.satisfied_by or self.conflicts_with
  543. dist_path = normalize_path(dist.location)
  544. if not dist_is_local(dist):
  545. logger.info(
  546. "Not uninstalling %s at %s, outside environment %s",
  547. dist.key,
  548. dist_path,
  549. sys.prefix,
  550. )
  551. self.nothing_to_uninstall = True
  552. return
  553. if dist_path in get_stdlib():
  554. logger.info(
  555. "Not uninstalling %s at %s, as it is in the standard library.",
  556. dist.key,
  557. dist_path,
  558. )
  559. self.nothing_to_uninstall = True
  560. return
  561. paths_to_remove = UninstallPathSet(dist)
  562. develop_egg_link = egg_link_path(dist)
  563. develop_egg_link_egg_info = '{0}.egg-info'.format(
  564. pkg_resources.to_filename(dist.project_name))
  565. egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info)
  566. # Special case for distutils installed package
  567. distutils_egg_info = getattr(dist._provider, 'path', None)
  568. # Uninstall cases order do matter as in the case of 2 installs of the
  569. # same package, pip needs to uninstall the currently detected version
  570. if (egg_info_exists and dist.egg_info.endswith('.egg-info') and
  571. not dist.egg_info.endswith(develop_egg_link_egg_info)):
  572. # if dist.egg_info.endswith(develop_egg_link_egg_info), we
  573. # are in fact in the develop_egg_link case
  574. paths_to_remove.add(dist.egg_info)
  575. if dist.has_metadata('installed-files.txt'):
  576. for installed_file in dist.get_metadata(
  577. 'installed-files.txt').splitlines():
  578. path = os.path.normpath(
  579. os.path.join(dist.egg_info, installed_file)
  580. )
  581. paths_to_remove.add(path)
  582. # FIXME: need a test for this elif block
  583. # occurs with --single-version-externally-managed/--record outside
  584. # of pip
  585. elif dist.has_metadata('top_level.txt'):
  586. if dist.has_metadata('namespace_packages.txt'):
  587. namespaces = dist.get_metadata('namespace_packages.txt')
  588. else:
  589. namespaces = []
  590. for top_level_pkg in [
  591. p for p
  592. in dist.get_metadata('top_level.txt').splitlines()
  593. if p and p not in namespaces]:
  594. path = os.path.join(dist.location, top_level_pkg)
  595. paths_to_remove.add(path)
  596. paths_to_remove.add(path + '.py')
  597. paths_to_remove.add(path + '.pyc')
  598. paths_to_remove.add(path + '.pyo')
  599. elif distutils_egg_info:
  600. warnings.warn(
  601. "Uninstalling a distutils installed project ({0}) has been "
  602. "deprecated and will be removed in a future version. This is "
  603. "due to the fact that uninstalling a distutils project will "
  604. "only partially uninstall the project.".format(self.name),
  605. RemovedInPip10Warning,
  606. )
  607. paths_to_remove.add(distutils_egg_info)
  608. elif dist.location.endswith('.egg'):
  609. # package installed by easy_install
  610. # We cannot match on dist.egg_name because it can slightly vary
  611. # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
  612. paths_to_remove.add(dist.location)
  613. easy_install_egg = os.path.split(dist.location)[1]
  614. easy_install_pth = os.path.join(os.path.dirname(dist.location),
  615. 'easy-install.pth')
  616. paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg)
  617. elif egg_info_exists and dist.egg_info.endswith('.dist-info'):
  618. for path in pip.wheel.uninstallation_paths(dist):
  619. paths_to_remove.add(path)
  620. elif develop_egg_link:
  621. # develop egg
  622. with open(develop_egg_link, 'r') as fh:
  623. link_pointer = os.path.normcase(fh.readline().strip())
  624. assert (link_pointer == dist.location), (
  625. 'Egg-link %s does not match installed location of %s '
  626. '(at %s)' % (link_pointer, self.name, dist.location)
  627. )
  628. paths_to_remove.add(develop_egg_link)
  629. easy_install_pth = os.path.join(os.path.dirname(develop_egg_link),
  630. 'easy-install.pth')
  631. paths_to_remove.add_pth(easy_install_pth, dist.location)
  632. else:
  633. logger.debug(
  634. 'Not sure how to uninstall: %s - Check: %s',
  635. dist, dist.location)
  636. # find distutils scripts= scripts
  637. if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'):
  638. for script in dist.metadata_listdir('scripts'):
  639. if dist_in_usersite(dist):
  640. bin_dir = bin_user
  641. else:
  642. bin_dir = bin_py
  643. paths_to_remove.add(os.path.join(bin_dir, script))
  644. if WINDOWS:
  645. paths_to_remove.add(os.path.join(bin_dir, script) + '.bat')
  646. # find console_scripts
  647. if dist.has_metadata('entry_points.txt'):
  648. if six.PY2:
  649. options = {}
  650. else:
  651. options = {"delimiters": ('=', )}
  652. config = configparser.SafeConfigParser(**options)
  653. config.readfp(
  654. FakeFile(dist.get_metadata_lines('entry_points.txt'))
  655. )
  656. if config.has_section('console_scripts'):
  657. for name, value in config.items('console_scripts'):
  658. if dist_in_usersite(dist):
  659. bin_dir = bin_user
  660. else:
  661. bin_dir = bin_py
  662. paths_to_remove.add(os.path.join(bin_dir, name))
  663. if WINDOWS:
  664. paths_to_remove.add(
  665. os.path.join(bin_dir, name) + '.exe'
  666. )
  667. paths_to_remove.add(
  668. os.path.join(bin_dir, name) + '.exe.manifest'
  669. )
  670. paths_to_remove.add(
  671. os.path.join(bin_dir, name) + '-script.py'
  672. )
  673. paths_to_remove.remove(auto_confirm)
  674. self.uninstalled = paths_to_remove
  675. def rollback_uninstall(self):
  676. if self.uninstalled:
  677. self.uninstalled.rollback()
  678. else:
  679. logger.error(
  680. "Can't rollback %s, nothing uninstalled.", self.name,
  681. )
  682. def commit_uninstall(self):
  683. if self.uninstalled:
  684. self.uninstalled.commit()
  685. elif not self.nothing_to_uninstall:
  686. logger.error(
  687. "Can't commit %s, nothing uninstalled.", self.name,
  688. )
  689. def archive(self, build_dir):
  690. assert self.source_dir
  691. create_archive = True
  692. archive_name = '%s-%s.zip' % (self.name, self.pkg_info()["version"])
  693. archive_path = os.path.join(build_dir, archive_name)
  694. if os.path.exists(archive_path):
  695. response = ask_path_exists(
  696. 'The file %s exists. (i)gnore, (w)ipe, (b)ackup, (a)bort ' %
  697. display_path(archive_path), ('i', 'w', 'b', 'a'))
  698. if response == 'i':
  699. create_archive = False
  700. elif response == 'w':
  701. logger.warning('Deleting %s', display_path(archive_path))
  702. os.remove(archive_path)
  703. elif response == 'b':
  704. dest_file = backup_dir(archive_path)
  705. logger.warning(
  706. 'Backing up %s to %s',
  707. display_path(archive_path),
  708. display_path(dest_file),
  709. )
  710. shutil.move(archive_path, dest_file)
  711. elif response == 'a':
  712. sys.exit(-1)
  713. if create_archive:
  714. zip = zipfile.ZipFile(
  715. archive_path, 'w', zipfile.ZIP_DEFLATED,
  716. allowZip64=True
  717. )
  718. dir = os.path.normcase(os.path.abspath(self.setup_py_dir))
  719. for dirpath, dirnames, filenames in os.walk(dir):
  720. if 'pip-egg-info' in dirnames:
  721. dirnames.remove('pip-egg-info')
  722. for dirname in dirnames:
  723. dirname = os.path.join(dirpath, dirname)
  724. name = self._clean_zip_name(dirname, dir)
  725. zipdir = zipfile.ZipInfo(self.name + '/' + name + '/')
  726. zipdir.external_attr = 0x1ED << 16 # 0o755
  727. zip.writestr(zipdir, '')
  728. for filename in filenames:
  729. if filename == PIP_DELETE_MARKER_FILENAME:
  730. continue
  731. filename = os.path.join(dirpath, filename)
  732. name = self._clean_zip_name(filename, dir)
  733. zip.write(filename, self.name + '/' + name)
  734. zip.close()
  735. logger.info('Saved %s', display_path(archive_path))
  736. def _clean_zip_name(self, name, prefix):
  737. assert name.startswith(prefix + os.path.sep), (
  738. "name %r doesn't start with prefix %r" % (name, prefix)
  739. )
  740. name = name[len(prefix) + 1:]
  741. name = name.replace(os.path.sep, '/')
  742. return name
  743. def match_markers(self, extras_requested=None):
  744. if not extras_requested:
  745. # Provide an extra to safely evaluate the markers
  746. # without matching any extra
  747. extras_requested = ('',)
  748. if self.markers is not None:
  749. return any(
  750. self.markers.evaluate({'extra': extra})
  751. for extra in extras_requested)
  752. else:
  753. return True
  754. def install(self, install_options, global_options=[], root=None,
  755. prefix=None):
  756. if self.editable:
  757. self.install_editable(
  758. install_options, global_options, prefix=prefix)
  759. return
  760. if self.is_wheel:
  761. version = pip.wheel.wheel_version(self.source_dir)
  762. pip.wheel.check_compatibility(version, self.name)
  763. self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  764. self.install_succeeded = True
  765. return
  766. # Extend the list of global and install options passed on to
  767. # the setup.py call with the ones from the requirements file.
  768. # Options specified in requirements file override those
  769. # specified on the command line, since the last option given
  770. # to setup.py is the one that is used.
  771. global_options += self.options.get('global_options', [])
  772. install_options += self.options.get('install_options', [])
  773. if self.isolated:
  774. global_options = list(global_options) + ["--no-user-cfg"]
  775. temp_location = tempfile.mkdtemp('-record', 'pip-')
  776. record_filename = os.path.join(temp_location, 'install-record.txt')
  777. try:
  778. install_args = self.get_install_args(
  779. global_options, record_filename, root, prefix)
  780. msg = 'Running setup.py install for %s' % (self.name,)
  781. with open_spinner(msg) as spinner:
  782. with indent_log():
  783. call_subprocess(
  784. install_args + install_options,
  785. cwd=self.setup_py_dir,
  786. show_stdout=False,
  787. spinner=spinner,
  788. )
  789. if not os.path.exists(record_filename):
  790. logger.debug('Record file %s not found', record_filename)
  791. return
  792. self.install_succeeded = True
  793. if self.as_egg:
  794. # there's no --always-unzip option we can pass to install
  795. # command so we unable to save the installed-files.txt
  796. return
  797. def prepend_root(path):
  798. if root is None or not os.path.isabs(path):
  799. return path
  800. else:
  801. return change_root(root, path)
  802. with open(record_filename) as f:
  803. for line in f:
  804. directory = os.path.dirname(line)
  805. if directory.endswith('.egg-info'):
  806. egg_info_dir = prepend_root(directory)
  807. break
  808. else:
  809. logger.warning(
  810. 'Could not find .egg-info directory in install record'
  811. ' for %s',
  812. self,
  813. )
  814. # FIXME: put the record somewhere
  815. # FIXME: should this be an error?
  816. return
  817. new_lines = []
  818. with open(record_filename) as f:
  819. for line in f:
  820. filename = line.strip()
  821. if os.path.isdir(filename):
  822. filename += os.path.sep
  823. new_lines.append(
  824. os.path.relpath(
  825. prepend_root(filename), egg_info_dir)
  826. )
  827. inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt')
  828. with open(inst_files_path, 'w') as f:
  829. f.write('\n'.join(new_lines) + '\n')
  830. finally:
  831. if os.path.exists(record_filename):
  832. os.remove(record_filename)
  833. rmtree(temp_location)
  834. def ensure_has_source_dir(self, parent_dir):
  835. """Ensure that a source_dir is set.
  836. This will create a temporary build dir if the name of the requirement
  837. isn't known yet.
  838. :param parent_dir: The ideal pip parent_dir for the source_dir.
  839. Generally src_dir for editables and build_dir for sdists.
  840. :return: self.source_dir
  841. """
  842. if self.source_dir is None:
  843. self.source_dir = self.build_location(parent_dir)
  844. return self.source_dir
  845. def get_install_args(self, global_options, record_filename, root, prefix):
  846. install_args = [sys.executable, "-u"]
  847. install_args.append('-c')
  848. install_args.append(SETUPTOOLS_SHIM % self.setup_py)
  849. install_args += list(global_options) + \
  850. ['install', '--record', record_filename]
  851. if not self.as_egg:
  852. install_args += ['--single-version-externally-managed']
  853. if root is not None:
  854. install_args += ['--root', root]
  855. if prefix is not None:
  856. install_args += ['--prefix', prefix]
  857. if self.pycompile:
  858. install_args += ["--compile"]
  859. else:
  860. install_args += ["--no-compile"]
  861. if running_under_virtualenv():
  862. py_ver_str = 'python' + sysconfig.get_python_version()
  863. install_args += ['--install-headers',
  864. os.path.join(sys.prefix, 'include', 'site',
  865. py_ver_str, self.name)]
  866. return install_args
  867. def remove_temporary_source(self):
  868. """Remove the source files from this requirement, if they are marked
  869. for deletion"""
  870. if self.source_dir and os.path.exists(
  871. os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)):
  872. logger.debug('Removing source in %s', self.source_dir)
  873. rmtree(self.source_dir)
  874. self.source_dir = None
  875. if self._temp_build_dir and os.path.exists(self._temp_build_dir):
  876. rmtree(self._temp_build_dir)
  877. self._temp_build_dir = None
  878. def install_editable(self, install_options,
  879. global_options=(), prefix=None):
  880. logger.info('Running setup.py develop for %s', self.name)
  881. if self.isolated:
  882. global_options = list(global_options) + ["--no-user-cfg"]
  883. if prefix:
  884. prefix_param = ['--prefix={0}'.format(prefix)]
  885. install_options = list(install_options) + prefix_param
  886. with indent_log():
  887. # FIXME: should we do --install-headers here too?
  888. call_subprocess(
  889. [
  890. sys.executable,
  891. '-c',
  892. SETUPTOOLS_SHIM % self.setup_py
  893. ] +
  894. list(global_options) +
  895. ['develop', '--no-deps'] +
  896. list(install_options),
  897. cwd=self.setup_py_dir,
  898. show_stdout=False)
  899. self.install_succeeded = True
  900. def check_if_exists(self):
  901. """Find an installed distribution that satisfies or conflicts
  902. with this requirement, and set self.satisfied_by or
  903. self.conflicts_with appropriately.
  904. """
  905. if self.req is None:
  906. return False
  907. try:
  908. # get_distribution() will resolve the entire list of requirements
  909. # anyway, and we've already determined that we need the requirement
  910. # in question, so strip the marker so that we don't try to
  911. # evaluate it.
  912. no_marker = Requirement(str(self.req))
  913. no_marker.marker = None
  914. self.satisfied_by = pkg_resources.get_distribution(str(no_marker))
  915. if self.editable and self.satisfied_by:
  916. self.conflicts_with = self.satisfied_by
  917. # when installing editables, nothing pre-existing should ever
  918. # satisfy
  919. self.satisfied_by = None
  920. return True
  921. except pkg_resources.DistributionNotFound:
  922. return False
  923. except pkg_resources.VersionConflict:
  924. existing_dist = pkg_resources.get_distribution(
  925. self.req.name
  926. )
  927. if self.use_user_site:
  928. if dist_in_usersite(existing_dist):
  929. self.conflicts_with = existing_dist
  930. elif (running_under_virtualenv() and
  931. dist_in_site_packages(existing_dist)):
  932. raise InstallationError(
  933. "Will not install to the user site because it will "
  934. "lack sys.path precedence to %s in %s" %
  935. (existing_dist.project_name, existing_dist.location)
  936. )
  937. else:
  938. self.conflicts_with = existing_dist
  939. return True
  940. @property
  941. def is_wheel(self):
  942. return self.link and self.link.is_wheel
  943. def move_wheel_files(self, wheeldir, root=None, prefix=None):
  944. move_wheel_files(
  945. self.name, self.req, wheeldir,
  946. user=self.use_user_site,
  947. home=self.target_dir,
  948. root=root,
  949. prefix=prefix,
  950. pycompile=self.pycompile,
  951. isolated=self.isolated,
  952. )
  953. def get_dist(self):
  954. """Return a pkg_resources.Distribution built from self.egg_info_path"""
  955. egg_info = self.egg_info_path('').rstrip('/')
  956. base_dir = os.path.dirname(egg_info)
  957. metadata = pkg_resources.PathMetadata(base_dir, egg_info)
  958. dist_name = os.path.splitext(os.path.basename(egg_info))[0]
  959. return pkg_resources.Distribution(
  960. os.path.dirname(egg_info),
  961. project_name=dist_name,
  962. metadata=metadata)
  963. @property
  964. def has_hash_options(self):
  965. """Return whether any known-good hashes are specified as options.
  966. These activate --require-hashes mode; hashes specified as part of a
  967. URL do not.
  968. """
  969. return bool(self.options.get('hashes', {}))
  970. def hashes(self, trust_internet=True):
  971. """Return a hash-comparer that considers my option- and URL-based
  972. hashes to be known-good.
  973. Hashes in URLs--ones embedded in the requirements file, not ones
  974. downloaded from an index server--are almost peers with ones from
  975. flags. They satisfy --require-hashes (whether it was implicitly or
  976. explicitly activated) but do not activate it. md5 and sha224 are not
  977. allowed in flags, which should nudge people toward good algos. We
  978. always OR all hashes together, even ones from URLs.
  979. :param trust_internet: Whether to trust URL-based (#md5=...) hashes
  980. downloaded from the internet, as by populate_link()
  981. """
  982. good_hashes = self.options.get('hashes', {}).copy()
  983. link = self.link if trust_internet else self.original_link
  984. if link and link.hash:
  985. good_hashes.setdefault(link.hash_name, []).append(link.hash)
  986. return Hashes(good_hashes)
  987. def _strip_postfix(req):
  988. """
  989. Strip req postfix ( -dev, 0.2, etc )
  990. """
  991. # FIXME: use package_to_requirement?
  992. match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req)
  993. if match:
  994. # Strip off -dev, -0.2, etc.
  995. req = match.group(1)
  996. return req
  997. def parse_editable(editable_req, default_vcs=None):
  998. """Parses an editable requirement into:
  999. - a requirement name
  1000. - an URL
  1001. - extras
  1002. - editable options
  1003. Accepted requirements:
  1004. svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
  1005. .[some_extra]
  1006. """
  1007. from pip.index import Link
  1008. url = editable_req
  1009. extras = None
  1010. # If a file path is specified with extras, strip off the extras.
  1011. m = re.match(r'^(.+)(\[[^\]]+\])$', url)
  1012. if m:
  1013. url_no_extras = m.group(1)
  1014. extras = m.group(2)
  1015. else:
  1016. url_no_extras = url
  1017. if os.path.isdir(url_no_extras):
  1018. if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
  1019. raise InstallationError(
  1020. "Directory %r is not installable. File 'setup.py' not found." %
  1021. url_no_extras
  1022. )
  1023. # Treating it as code that has already been checked out
  1024. url_no_extras = path_to_url(url_no_extras)
  1025. if url_no_extras.lower().startswith('file:'):
  1026. package_name = Link(url_no_extras).egg_fragment
  1027. if extras:
  1028. return (
  1029. package_name,
  1030. url_no_extras,
  1031. Requirement("placeholder" + extras.lower()).extras,
  1032. )
  1033. else:
  1034. return package_name, url_no_extras, None
  1035. for version_control in vcs:
  1036. if url.lower().startswith('%s:' % version_control):
  1037. url = '%s+%s' % (version_control, url)
  1038. break
  1039. if '+' not in url:
  1040. if default_vcs:
  1041. warnings.warn(
  1042. "--default-vcs has been deprecated and will be removed in "
  1043. "the future.",
  1044. RemovedInPip10Warning,
  1045. )
  1046. url = default_vcs + '+' + url
  1047. else:
  1048. raise InstallationError(
  1049. '%s should either be a path to a local project or a VCS url '
  1050. 'beginning with svn+, git+, hg+, or bzr+' %
  1051. editable_req
  1052. )
  1053. vc_type = url.split('+', 1)[0].lower()
  1054. if not vcs.get_backend(vc_type):
  1055. error_message = 'For --editable=%s only ' % editable_req + \
  1056. ', '.join([backend.name + '+URL' for backend in vcs.backends]) + \
  1057. ' is currently supported'
  1058. raise InstallationError(error_message)
  1059. package_name = Link(url).egg_fragment
  1060. if not package_name:
  1061. raise InstallationError(
  1062. "Could not detect requirement name, please specify one with #egg="
  1063. )
  1064. if not package_name:
  1065. raise InstallationError(
  1066. '--editable=%s is not the right format; it must have '
  1067. '#egg=Package' % editable_req
  1068. )
  1069. return _strip_postfix(package_name), url, None