req_install.py 44 KB

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