req_install.py 42 KB

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