PageRenderTime 31ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/venv/lib/python2.7/site-packages/pip/_vendor/distlib/wheel.py

https://gitlab.com/ismailam/openexport
Python | 976 lines | 866 code | 48 blank | 62 comment | 139 complexity | 0d0ecea38d12f3e0aa0c94d0d188f3c5 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2014 Vinay Sajip.
  4. # Licensed to the Python Software Foundation under a contributor agreement.
  5. # See LICENSE.txt and CONTRIBUTORS.txt.
  6. #
  7. from __future__ import unicode_literals
  8. import base64
  9. import codecs
  10. import datetime
  11. import distutils.util
  12. from email import message_from_file
  13. import hashlib
  14. import imp
  15. import json
  16. import logging
  17. import os
  18. import posixpath
  19. import re
  20. import shutil
  21. import sys
  22. import tempfile
  23. import zipfile
  24. from . import __version__, DistlibException
  25. from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
  26. from .database import InstalledDistribution
  27. from .metadata import Metadata, METADATA_FILENAME
  28. from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,
  29. cached_property, get_cache_base, read_exports, tempdir)
  30. from .version import NormalizedVersion, UnsupportedVersionError
  31. logger = logging.getLogger(__name__)
  32. cache = None # created when needed
  33. if hasattr(sys, 'pypy_version_info'):
  34. IMP_PREFIX = 'pp'
  35. elif sys.platform.startswith('java'):
  36. IMP_PREFIX = 'jy'
  37. elif sys.platform == 'cli':
  38. IMP_PREFIX = 'ip'
  39. else:
  40. IMP_PREFIX = 'cp'
  41. VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
  42. if not VER_SUFFIX: # pragma: no cover
  43. VER_SUFFIX = '%s%s' % sys.version_info[:2]
  44. PYVER = 'py' + VER_SUFFIX
  45. IMPVER = IMP_PREFIX + VER_SUFFIX
  46. ARCH = distutils.util.get_platform().replace('-', '_').replace('.', '_')
  47. ABI = sysconfig.get_config_var('SOABI')
  48. if ABI and ABI.startswith('cpython-'):
  49. ABI = ABI.replace('cpython-', 'cp')
  50. else:
  51. def _derive_abi():
  52. parts = ['cp', VER_SUFFIX]
  53. if sysconfig.get_config_var('Py_DEBUG'):
  54. parts.append('d')
  55. if sysconfig.get_config_var('WITH_PYMALLOC'):
  56. parts.append('m')
  57. if sysconfig.get_config_var('Py_UNICODE_SIZE') == 4:
  58. parts.append('u')
  59. return ''.join(parts)
  60. ABI = _derive_abi()
  61. del _derive_abi
  62. FILENAME_RE = re.compile(r'''
  63. (?P<nm>[^-]+)
  64. -(?P<vn>\d+[^-]*)
  65. (-(?P<bn>\d+[^-]*))?
  66. -(?P<py>\w+\d+(\.\w+\d+)*)
  67. -(?P<bi>\w+)
  68. -(?P<ar>\w+)
  69. \.whl$
  70. ''', re.IGNORECASE | re.VERBOSE)
  71. NAME_VERSION_RE = re.compile(r'''
  72. (?P<nm>[^-]+)
  73. -(?P<vn>\d+[^-]*)
  74. (-(?P<bn>\d+[^-]*))?$
  75. ''', re.IGNORECASE | re.VERBOSE)
  76. SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
  77. SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
  78. SHEBANG_PYTHON = b'#!python'
  79. SHEBANG_PYTHONW = b'#!pythonw'
  80. if os.sep == '/':
  81. to_posix = lambda o: o
  82. else:
  83. to_posix = lambda o: o.replace(os.sep, '/')
  84. class Mounter(object):
  85. def __init__(self):
  86. self.impure_wheels = {}
  87. self.libs = {}
  88. def add(self, pathname, extensions):
  89. self.impure_wheels[pathname] = extensions
  90. self.libs.update(extensions)
  91. def remove(self, pathname):
  92. extensions = self.impure_wheels.pop(pathname)
  93. for k, v in extensions:
  94. if k in self.libs:
  95. del self.libs[k]
  96. def find_module(self, fullname, path=None):
  97. if fullname in self.libs:
  98. result = self
  99. else:
  100. result = None
  101. return result
  102. def load_module(self, fullname):
  103. if fullname in sys.modules:
  104. result = sys.modules[fullname]
  105. else:
  106. if fullname not in self.libs:
  107. raise ImportError('unable to find extension for %s' % fullname)
  108. result = imp.load_dynamic(fullname, self.libs[fullname])
  109. result.__loader__ = self
  110. parts = fullname.rsplit('.', 1)
  111. if len(parts) > 1:
  112. result.__package__ = parts[0]
  113. return result
  114. _hook = Mounter()
  115. class Wheel(object):
  116. """
  117. Class to build and install from Wheel files (PEP 427).
  118. """
  119. wheel_version = (1, 1)
  120. hash_kind = 'sha256'
  121. def __init__(self, filename=None, sign=False, verify=False):
  122. """
  123. Initialise an instance using a (valid) filename.
  124. """
  125. self.sign = sign
  126. self.should_verify = verify
  127. self.buildver = ''
  128. self.pyver = [PYVER]
  129. self.abi = ['none']
  130. self.arch = ['any']
  131. self.dirname = os.getcwd()
  132. if filename is None:
  133. self.name = 'dummy'
  134. self.version = '0.1'
  135. self._filename = self.filename
  136. else:
  137. m = NAME_VERSION_RE.match(filename)
  138. if m:
  139. info = m.groupdict('')
  140. self.name = info['nm']
  141. # Reinstate the local version separator
  142. self.version = info['vn'].replace('_', '-')
  143. self.buildver = info['bn']
  144. self._filename = self.filename
  145. else:
  146. dirname, filename = os.path.split(filename)
  147. m = FILENAME_RE.match(filename)
  148. if not m:
  149. raise DistlibException('Invalid name or '
  150. 'filename: %r' % filename)
  151. if dirname:
  152. self.dirname = os.path.abspath(dirname)
  153. self._filename = filename
  154. info = m.groupdict('')
  155. self.name = info['nm']
  156. self.version = info['vn']
  157. self.buildver = info['bn']
  158. self.pyver = info['py'].split('.')
  159. self.abi = info['bi'].split('.')
  160. self.arch = info['ar'].split('.')
  161. @property
  162. def filename(self):
  163. """
  164. Build and return a filename from the various components.
  165. """
  166. if self.buildver:
  167. buildver = '-' + self.buildver
  168. else:
  169. buildver = ''
  170. pyver = '.'.join(self.pyver)
  171. abi = '.'.join(self.abi)
  172. arch = '.'.join(self.arch)
  173. # replace - with _ as a local version separator
  174. version = self.version.replace('-', '_')
  175. return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
  176. pyver, abi, arch)
  177. @property
  178. def exists(self):
  179. path = os.path.join(self.dirname, self.filename)
  180. return os.path.isfile(path)
  181. @property
  182. def tags(self):
  183. for pyver in self.pyver:
  184. for abi in self.abi:
  185. for arch in self.arch:
  186. yield pyver, abi, arch
  187. @cached_property
  188. def metadata(self):
  189. pathname = os.path.join(self.dirname, self.filename)
  190. name_ver = '%s-%s' % (self.name, self.version)
  191. info_dir = '%s.dist-info' % name_ver
  192. wrapper = codecs.getreader('utf-8')
  193. with ZipFile(pathname, 'r') as zf:
  194. wheel_metadata = self.get_wheel_metadata(zf)
  195. wv = wheel_metadata['Wheel-Version'].split('.', 1)
  196. file_version = tuple([int(i) for i in wv])
  197. if file_version < (1, 1):
  198. fn = 'METADATA'
  199. else:
  200. fn = METADATA_FILENAME
  201. try:
  202. metadata_filename = posixpath.join(info_dir, fn)
  203. with zf.open(metadata_filename) as bf:
  204. wf = wrapper(bf)
  205. result = Metadata(fileobj=wf)
  206. except KeyError:
  207. raise ValueError('Invalid wheel, because %s is '
  208. 'missing' % fn)
  209. return result
  210. def get_wheel_metadata(self, zf):
  211. name_ver = '%s-%s' % (self.name, self.version)
  212. info_dir = '%s.dist-info' % name_ver
  213. metadata_filename = posixpath.join(info_dir, 'WHEEL')
  214. with zf.open(metadata_filename) as bf:
  215. wf = codecs.getreader('utf-8')(bf)
  216. message = message_from_file(wf)
  217. return dict(message)
  218. @cached_property
  219. def info(self):
  220. pathname = os.path.join(self.dirname, self.filename)
  221. with ZipFile(pathname, 'r') as zf:
  222. result = self.get_wheel_metadata(zf)
  223. return result
  224. def process_shebang(self, data):
  225. m = SHEBANG_RE.match(data)
  226. if m:
  227. end = m.end()
  228. shebang, data_after_shebang = data[:end], data[end:]
  229. # Preserve any arguments after the interpreter
  230. if b'pythonw' in shebang.lower():
  231. shebang_python = SHEBANG_PYTHONW
  232. else:
  233. shebang_python = SHEBANG_PYTHON
  234. m = SHEBANG_DETAIL_RE.match(shebang)
  235. if m:
  236. args = b' ' + m.groups()[-1]
  237. else:
  238. args = b''
  239. shebang = shebang_python + args
  240. data = shebang + data_after_shebang
  241. else:
  242. cr = data.find(b'\r')
  243. lf = data.find(b'\n')
  244. if cr < 0 or cr > lf:
  245. term = b'\n'
  246. else:
  247. if data[cr:cr + 2] == b'\r\n':
  248. term = b'\r\n'
  249. else:
  250. term = b'\r'
  251. data = SHEBANG_PYTHON + term + data
  252. return data
  253. def get_hash(self, data, hash_kind=None):
  254. if hash_kind is None:
  255. hash_kind = self.hash_kind
  256. try:
  257. hasher = getattr(hashlib, hash_kind)
  258. except AttributeError:
  259. raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
  260. result = hasher(data).digest()
  261. result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
  262. return hash_kind, result
  263. def write_record(self, records, record_path, base):
  264. with CSVWriter(record_path) as writer:
  265. for row in records:
  266. writer.writerow(row)
  267. p = to_posix(os.path.relpath(record_path, base))
  268. writer.writerow((p, '', ''))
  269. def write_records(self, info, libdir, archive_paths):
  270. records = []
  271. distinfo, info_dir = info
  272. hasher = getattr(hashlib, self.hash_kind)
  273. for ap, p in archive_paths:
  274. with open(p, 'rb') as f:
  275. data = f.read()
  276. digest = '%s=%s' % self.get_hash(data)
  277. size = os.path.getsize(p)
  278. records.append((ap, digest, size))
  279. p = os.path.join(distinfo, 'RECORD')
  280. self.write_record(records, p, libdir)
  281. ap = to_posix(os.path.join(info_dir, 'RECORD'))
  282. archive_paths.append((ap, p))
  283. def build_zip(self, pathname, archive_paths):
  284. with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
  285. for ap, p in archive_paths:
  286. logger.debug('Wrote %s to %s in wheel', p, ap)
  287. zf.write(p, ap)
  288. def build(self, paths, tags=None, wheel_version=None):
  289. """
  290. Build a wheel from files in specified paths, and use any specified tags
  291. when determining the name of the wheel.
  292. """
  293. if tags is None:
  294. tags = {}
  295. libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
  296. if libkey == 'platlib':
  297. is_pure = 'false'
  298. default_pyver = [IMPVER]
  299. default_abi = [ABI]
  300. default_arch = [ARCH]
  301. else:
  302. is_pure = 'true'
  303. default_pyver = [PYVER]
  304. default_abi = ['none']
  305. default_arch = ['any']
  306. self.pyver = tags.get('pyver', default_pyver)
  307. self.abi = tags.get('abi', default_abi)
  308. self.arch = tags.get('arch', default_arch)
  309. libdir = paths[libkey]
  310. name_ver = '%s-%s' % (self.name, self.version)
  311. data_dir = '%s.data' % name_ver
  312. info_dir = '%s.dist-info' % name_ver
  313. archive_paths = []
  314. # First, stuff which is not in site-packages
  315. for key in ('data', 'headers', 'scripts'):
  316. if key not in paths:
  317. continue
  318. path = paths[key]
  319. if os.path.isdir(path):
  320. for root, dirs, files in os.walk(path):
  321. for fn in files:
  322. p = fsdecode(os.path.join(root, fn))
  323. rp = os.path.relpath(p, path)
  324. ap = to_posix(os.path.join(data_dir, key, rp))
  325. archive_paths.append((ap, p))
  326. if key == 'scripts' and not p.endswith('.exe'):
  327. with open(p, 'rb') as f:
  328. data = f.read()
  329. data = self.process_shebang(data)
  330. with open(p, 'wb') as f:
  331. f.write(data)
  332. # Now, stuff which is in site-packages, other than the
  333. # distinfo stuff.
  334. path = libdir
  335. distinfo = None
  336. for root, dirs, files in os.walk(path):
  337. if root == path:
  338. # At the top level only, save distinfo for later
  339. # and skip it for now
  340. for i, dn in enumerate(dirs):
  341. dn = fsdecode(dn)
  342. if dn.endswith('.dist-info'):
  343. distinfo = os.path.join(root, dn)
  344. del dirs[i]
  345. break
  346. assert distinfo, '.dist-info directory expected, not found'
  347. for fn in files:
  348. # comment out next suite to leave .pyc files in
  349. if fsdecode(fn).endswith(('.pyc', '.pyo')):
  350. continue
  351. p = os.path.join(root, fn)
  352. rp = to_posix(os.path.relpath(p, path))
  353. archive_paths.append((rp, p))
  354. # Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
  355. files = os.listdir(distinfo)
  356. for fn in files:
  357. if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
  358. p = fsdecode(os.path.join(distinfo, fn))
  359. ap = to_posix(os.path.join(info_dir, fn))
  360. archive_paths.append((ap, p))
  361. wheel_metadata = [
  362. 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
  363. 'Generator: distlib %s' % __version__,
  364. 'Root-Is-Purelib: %s' % is_pure,
  365. ]
  366. for pyver, abi, arch in self.tags:
  367. wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
  368. p = os.path.join(distinfo, 'WHEEL')
  369. with open(p, 'w') as f:
  370. f.write('\n'.join(wheel_metadata))
  371. ap = to_posix(os.path.join(info_dir, 'WHEEL'))
  372. archive_paths.append((ap, p))
  373. # Now, at last, RECORD.
  374. # Paths in here are archive paths - nothing else makes sense.
  375. self.write_records((distinfo, info_dir), libdir, archive_paths)
  376. # Now, ready to build the zip file
  377. pathname = os.path.join(self.dirname, self.filename)
  378. self.build_zip(pathname, archive_paths)
  379. return pathname
  380. def install(self, paths, maker, **kwargs):
  381. """
  382. Install a wheel to the specified paths. If kwarg ``warner`` is
  383. specified, it should be a callable, which will be called with two
  384. tuples indicating the wheel version of this software and the wheel
  385. version in the file, if there is a discrepancy in the versions.
  386. This can be used to issue any warnings to raise any exceptions.
  387. If kwarg ``lib_only`` is True, only the purelib/platlib files are
  388. installed, and the headers, scripts, data and dist-info metadata are
  389. not written.
  390. The return value is a :class:`InstalledDistribution` instance unless
  391. ``options.lib_only`` is True, in which case the return value is ``None``.
  392. """
  393. dry_run = maker.dry_run
  394. warner = kwargs.get('warner')
  395. lib_only = kwargs.get('lib_only', False)
  396. pathname = os.path.join(self.dirname, self.filename)
  397. name_ver = '%s-%s' % (self.name, self.version)
  398. data_dir = '%s.data' % name_ver
  399. info_dir = '%s.dist-info' % name_ver
  400. metadata_name = posixpath.join(info_dir, METADATA_FILENAME)
  401. wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
  402. record_name = posixpath.join(info_dir, 'RECORD')
  403. wrapper = codecs.getreader('utf-8')
  404. with ZipFile(pathname, 'r') as zf:
  405. with zf.open(wheel_metadata_name) as bwf:
  406. wf = wrapper(bwf)
  407. message = message_from_file(wf)
  408. wv = message['Wheel-Version'].split('.', 1)
  409. file_version = tuple([int(i) for i in wv])
  410. if (file_version != self.wheel_version) and warner:
  411. warner(self.wheel_version, file_version)
  412. if message['Root-Is-Purelib'] == 'true':
  413. libdir = paths['purelib']
  414. else:
  415. libdir = paths['platlib']
  416. records = {}
  417. with zf.open(record_name) as bf:
  418. with CSVReader(stream=bf) as reader:
  419. for row in reader:
  420. p = row[0]
  421. records[p] = row
  422. data_pfx = posixpath.join(data_dir, '')
  423. info_pfx = posixpath.join(info_dir, '')
  424. script_pfx = posixpath.join(data_dir, 'scripts', '')
  425. # make a new instance rather than a copy of maker's,
  426. # as we mutate it
  427. fileop = FileOperator(dry_run=dry_run)
  428. fileop.record = True # so we can rollback if needed
  429. bc = not sys.dont_write_bytecode # Double negatives. Lovely!
  430. outfiles = [] # for RECORD writing
  431. # for script copying/shebang processing
  432. workdir = tempfile.mkdtemp()
  433. # set target dir later
  434. # we default add_launchers to False, as the
  435. # Python Launcher should be used instead
  436. maker.source_dir = workdir
  437. maker.target_dir = None
  438. try:
  439. for zinfo in zf.infolist():
  440. arcname = zinfo.filename
  441. if isinstance(arcname, text_type):
  442. u_arcname = arcname
  443. else:
  444. u_arcname = arcname.decode('utf-8')
  445. # The signature file won't be in RECORD,
  446. # and we don't currently don't do anything with it
  447. if u_arcname.endswith('/RECORD.jws'):
  448. continue
  449. row = records[u_arcname]
  450. if row[2] and str(zinfo.file_size) != row[2]:
  451. raise DistlibException('size mismatch for '
  452. '%s' % u_arcname)
  453. if row[1]:
  454. kind, value = row[1].split('=', 1)
  455. with zf.open(arcname) as bf:
  456. data = bf.read()
  457. _, digest = self.get_hash(data, kind)
  458. if digest != value:
  459. raise DistlibException('digest mismatch for '
  460. '%s' % arcname)
  461. if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
  462. logger.debug('lib_only: skipping %s', u_arcname)
  463. continue
  464. is_script = (u_arcname.startswith(script_pfx)
  465. and not u_arcname.endswith('.exe'))
  466. if u_arcname.startswith(data_pfx):
  467. _, where, rp = u_arcname.split('/', 2)
  468. outfile = os.path.join(paths[where], convert_path(rp))
  469. else:
  470. # meant for site-packages.
  471. if u_arcname in (wheel_metadata_name, record_name):
  472. continue
  473. outfile = os.path.join(libdir, convert_path(u_arcname))
  474. if not is_script:
  475. with zf.open(arcname) as bf:
  476. fileop.copy_stream(bf, outfile)
  477. outfiles.append(outfile)
  478. # Double check the digest of the written file
  479. if not dry_run and row[1]:
  480. with open(outfile, 'rb') as bf:
  481. data = bf.read()
  482. _, newdigest = self.get_hash(data, kind)
  483. if newdigest != digest:
  484. raise DistlibException('digest mismatch '
  485. 'on write for '
  486. '%s' % outfile)
  487. if bc and outfile.endswith('.py'):
  488. try:
  489. pyc = fileop.byte_compile(outfile)
  490. outfiles.append(pyc)
  491. except Exception:
  492. # Don't give up if byte-compilation fails,
  493. # but log it and perhaps warn the user
  494. logger.warning('Byte-compilation failed',
  495. exc_info=True)
  496. else:
  497. fn = os.path.basename(convert_path(arcname))
  498. workname = os.path.join(workdir, fn)
  499. with zf.open(arcname) as bf:
  500. fileop.copy_stream(bf, workname)
  501. dn, fn = os.path.split(outfile)
  502. maker.target_dir = dn
  503. filenames = maker.make(fn)
  504. fileop.set_executable_mode(filenames)
  505. outfiles.extend(filenames)
  506. if lib_only:
  507. logger.debug('lib_only: returning None')
  508. dist = None
  509. else:
  510. # Generate scripts
  511. # Try to get pydist.json so we can see if there are
  512. # any commands to generate. If this fails (e.g. because
  513. # of a legacy wheel), log a warning but don't give up.
  514. commands = None
  515. file_version = self.info['Wheel-Version']
  516. if file_version == '1.0':
  517. # Use legacy info
  518. ep = posixpath.join(info_dir, 'entry_points.txt')
  519. try:
  520. with zf.open(ep) as bwf:
  521. epdata = read_exports(bwf)
  522. commands = {}
  523. for key in ('console', 'gui'):
  524. k = '%s_scripts' % key
  525. if k in epdata:
  526. commands['wrap_%s' % key] = d = {}
  527. for v in epdata[k].values():
  528. s = '%s:%s' % (v.prefix, v.suffix)
  529. if v.flags:
  530. s += ' %s' % v.flags
  531. d[v.name] = s
  532. except Exception:
  533. logger.warning('Unable to read legacy script '
  534. 'metadata, so cannot generate '
  535. 'scripts')
  536. else:
  537. try:
  538. with zf.open(metadata_name) as bwf:
  539. wf = wrapper(bwf)
  540. commands = json.load(wf).get('extensions')
  541. if commands:
  542. commands = commands.get('python.commands')
  543. except Exception:
  544. logger.warning('Unable to read JSON metadata, so '
  545. 'cannot generate scripts')
  546. if commands:
  547. console_scripts = commands.get('wrap_console', {})
  548. gui_scripts = commands.get('wrap_gui', {})
  549. if console_scripts or gui_scripts:
  550. script_dir = paths.get('scripts', '')
  551. if not os.path.isdir(script_dir):
  552. raise ValueError('Valid script path not '
  553. 'specified')
  554. maker.target_dir = script_dir
  555. for k, v in console_scripts.items():
  556. script = '%s = %s' % (k, v)
  557. filenames = maker.make(script)
  558. fileop.set_executable_mode(filenames)
  559. if gui_scripts:
  560. options = {'gui': True }
  561. for k, v in gui_scripts.items():
  562. script = '%s = %s' % (k, v)
  563. filenames = maker.make(script, options)
  564. fileop.set_executable_mode(filenames)
  565. p = os.path.join(libdir, info_dir)
  566. dist = InstalledDistribution(p)
  567. # Write SHARED
  568. paths = dict(paths) # don't change passed in dict
  569. del paths['purelib']
  570. del paths['platlib']
  571. paths['lib'] = libdir
  572. p = dist.write_shared_locations(paths, dry_run)
  573. if p:
  574. outfiles.append(p)
  575. # Write RECORD
  576. dist.write_installed_files(outfiles, paths['prefix'],
  577. dry_run)
  578. return dist
  579. except Exception: # pragma: no cover
  580. logger.exception('installation failed.')
  581. fileop.rollback()
  582. raise
  583. finally:
  584. shutil.rmtree(workdir)
  585. def _get_dylib_cache(self):
  586. global cache
  587. if cache is None:
  588. # Use native string to avoid issues on 2.x: see Python #20140.
  589. base = os.path.join(get_cache_base(), str('dylib-cache'),
  590. sys.version[:3])
  591. cache = Cache(base)
  592. return cache
  593. def _get_extensions(self):
  594. pathname = os.path.join(self.dirname, self.filename)
  595. name_ver = '%s-%s' % (self.name, self.version)
  596. info_dir = '%s.dist-info' % name_ver
  597. arcname = posixpath.join(info_dir, 'EXTENSIONS')
  598. wrapper = codecs.getreader('utf-8')
  599. result = []
  600. with ZipFile(pathname, 'r') as zf:
  601. try:
  602. with zf.open(arcname) as bf:
  603. wf = wrapper(bf)
  604. extensions = json.load(wf)
  605. cache = self._get_dylib_cache()
  606. prefix = cache.prefix_to_dir(pathname)
  607. cache_base = os.path.join(cache.base, prefix)
  608. if not os.path.isdir(cache_base):
  609. os.makedirs(cache_base)
  610. for name, relpath in extensions.items():
  611. dest = os.path.join(cache_base, convert_path(relpath))
  612. if not os.path.exists(dest):
  613. extract = True
  614. else:
  615. file_time = os.stat(dest).st_mtime
  616. file_time = datetime.datetime.fromtimestamp(file_time)
  617. info = zf.getinfo(relpath)
  618. wheel_time = datetime.datetime(*info.date_time)
  619. extract = wheel_time > file_time
  620. if extract:
  621. zf.extract(relpath, cache_base)
  622. result.append((name, dest))
  623. except KeyError:
  624. pass
  625. return result
  626. def is_compatible(self):
  627. """
  628. Determine if a wheel is compatible with the running system.
  629. """
  630. return is_compatible(self)
  631. def is_mountable(self):
  632. """
  633. Determine if a wheel is asserted as mountable by its metadata.
  634. """
  635. return True # for now - metadata details TBD
  636. def mount(self, append=False):
  637. pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
  638. if not self.is_compatible():
  639. msg = 'Wheel %s not compatible with this Python.' % pathname
  640. raise DistlibException(msg)
  641. if not self.is_mountable():
  642. msg = 'Wheel %s is marked as not mountable.' % pathname
  643. raise DistlibException(msg)
  644. if pathname in sys.path:
  645. logger.debug('%s already in path', pathname)
  646. else:
  647. if append:
  648. sys.path.append(pathname)
  649. else:
  650. sys.path.insert(0, pathname)
  651. extensions = self._get_extensions()
  652. if extensions:
  653. if _hook not in sys.meta_path:
  654. sys.meta_path.append(_hook)
  655. _hook.add(pathname, extensions)
  656. def unmount(self):
  657. pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
  658. if pathname not in sys.path:
  659. logger.debug('%s not in path', pathname)
  660. else:
  661. sys.path.remove(pathname)
  662. if pathname in _hook.impure_wheels:
  663. _hook.remove(pathname)
  664. if not _hook.impure_wheels:
  665. if _hook in sys.meta_path:
  666. sys.meta_path.remove(_hook)
  667. def verify(self):
  668. pathname = os.path.join(self.dirname, self.filename)
  669. name_ver = '%s-%s' % (self.name, self.version)
  670. data_dir = '%s.data' % name_ver
  671. info_dir = '%s.dist-info' % name_ver
  672. metadata_name = posixpath.join(info_dir, METADATA_FILENAME)
  673. wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
  674. record_name = posixpath.join(info_dir, 'RECORD')
  675. wrapper = codecs.getreader('utf-8')
  676. with ZipFile(pathname, 'r') as zf:
  677. with zf.open(wheel_metadata_name) as bwf:
  678. wf = wrapper(bwf)
  679. message = message_from_file(wf)
  680. wv = message['Wheel-Version'].split('.', 1)
  681. file_version = tuple([int(i) for i in wv])
  682. # TODO version verification
  683. records = {}
  684. with zf.open(record_name) as bf:
  685. with CSVReader(stream=bf) as reader:
  686. for row in reader:
  687. p = row[0]
  688. records[p] = row
  689. for zinfo in zf.infolist():
  690. arcname = zinfo.filename
  691. if isinstance(arcname, text_type):
  692. u_arcname = arcname
  693. else:
  694. u_arcname = arcname.decode('utf-8')
  695. if '..' in u_arcname:
  696. raise DistlibException('invalid entry in '
  697. 'wheel: %r' % u_arcname)
  698. # The signature file won't be in RECORD,
  699. # and we don't currently don't do anything with it
  700. if u_arcname.endswith('/RECORD.jws'):
  701. continue
  702. row = records[u_arcname]
  703. if row[2] and str(zinfo.file_size) != row[2]:
  704. raise DistlibException('size mismatch for '
  705. '%s' % u_arcname)
  706. if row[1]:
  707. kind, value = row[1].split('=', 1)
  708. with zf.open(arcname) as bf:
  709. data = bf.read()
  710. _, digest = self.get_hash(data, kind)
  711. if digest != value:
  712. raise DistlibException('digest mismatch for '
  713. '%s' % arcname)
  714. def update(self, modifier, dest_dir=None, **kwargs):
  715. """
  716. Update the contents of a wheel in a generic way. The modifier should
  717. be a callable which expects a dictionary argument: its keys are
  718. archive-entry paths, and its values are absolute filesystem paths
  719. where the contents the corresponding archive entries can be found. The
  720. modifier is free to change the contents of the files pointed to, add
  721. new entries and remove entries, before returning. This method will
  722. extract the entire contents of the wheel to a temporary location, call
  723. the modifier, and then use the passed (and possibly updated)
  724. dictionary to write a new wheel. If ``dest_dir`` is specified, the new
  725. wheel is written there -- otherwise, the original wheel is overwritten.
  726. The modifier should return True if it updated the wheel, else False.
  727. This method returns the same value the modifier returns.
  728. """
  729. def get_version(path_map, info_dir):
  730. version = path = None
  731. key = '%s/%s' % (info_dir, METADATA_FILENAME)
  732. if key not in path_map:
  733. key = '%s/PKG-INFO' % info_dir
  734. if key in path_map:
  735. path = path_map[key]
  736. version = Metadata(path=path).version
  737. return version, path
  738. def update_version(version, path):
  739. updated = None
  740. try:
  741. v = NormalizedVersion(version)
  742. i = version.find('-')
  743. if i < 0:
  744. updated = '%s+1' % version
  745. else:
  746. parts = [int(s) for s in version[i + 1:].split('.')]
  747. parts[-1] += 1
  748. updated = '%s+%s' % (version[:i],
  749. '.'.join(str(i) for i in parts))
  750. except UnsupportedVersionError:
  751. logger.debug('Cannot update non-compliant (PEP-440) '
  752. 'version %r', version)
  753. if updated:
  754. md = Metadata(path=path)
  755. md.version = updated
  756. legacy = not path.endswith(METADATA_FILENAME)
  757. md.write(path=path, legacy=legacy)
  758. logger.debug('Version updated from %r to %r', version,
  759. updated)
  760. pathname = os.path.join(self.dirname, self.filename)
  761. name_ver = '%s-%s' % (self.name, self.version)
  762. info_dir = '%s.dist-info' % name_ver
  763. record_name = posixpath.join(info_dir, 'RECORD')
  764. with tempdir() as workdir:
  765. with ZipFile(pathname, 'r') as zf:
  766. path_map = {}
  767. for zinfo in zf.infolist():
  768. arcname = zinfo.filename
  769. if isinstance(arcname, text_type):
  770. u_arcname = arcname
  771. else:
  772. u_arcname = arcname.decode('utf-8')
  773. if u_arcname == record_name:
  774. continue
  775. if '..' in u_arcname:
  776. raise DistlibException('invalid entry in '
  777. 'wheel: %r' % u_arcname)
  778. zf.extract(zinfo, workdir)
  779. path = os.path.join(workdir, convert_path(u_arcname))
  780. path_map[u_arcname] = path
  781. # Remember the version.
  782. original_version, _ = get_version(path_map, info_dir)
  783. # Files extracted. Call the modifier.
  784. modified = modifier(path_map, **kwargs)
  785. if modified:
  786. # Something changed - need to build a new wheel.
  787. current_version, path = get_version(path_map, info_dir)
  788. if current_version and (current_version == original_version):
  789. # Add or update local version to signify changes.
  790. update_version(current_version, path)
  791. # Decide where the new wheel goes.
  792. if dest_dir is None:
  793. fd, newpath = tempfile.mkstemp(suffix='.whl',
  794. prefix='wheel-update-',
  795. dir=workdir)
  796. os.close(fd)
  797. else:
  798. if not os.path.isdir(dest_dir):
  799. raise DistlibException('Not a directory: %r' % dest_dir)
  800. newpath = os.path.join(dest_dir, self.filename)
  801. archive_paths = list(path_map.items())
  802. distinfo = os.path.join(workdir, info_dir)
  803. info = distinfo, info_dir
  804. self.write_records(info, workdir, archive_paths)
  805. self.build_zip(newpath, archive_paths)
  806. if dest_dir is None:
  807. shutil.copyfile(newpath, pathname)
  808. return modified
  809. def compatible_tags():
  810. """
  811. Return (pyver, abi, arch) tuples compatible with this Python.
  812. """
  813. versions = [VER_SUFFIX]
  814. major = VER_SUFFIX[0]
  815. for minor in range(sys.version_info[1] - 1, - 1, -1):
  816. versions.append(''.join([major, str(minor)]))
  817. abis = []
  818. for suffix, _, _ in imp.get_suffixes():
  819. if suffix.startswith('.abi'):
  820. abis.append(suffix.split('.', 2)[1])
  821. abis.sort()
  822. if ABI != 'none':
  823. abis.insert(0, ABI)
  824. abis.append('none')
  825. result = []
  826. arches = [ARCH]
  827. if sys.platform == 'darwin':
  828. m = re.match('(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
  829. if m:
  830. name, major, minor, arch = m.groups()
  831. minor = int(minor)
  832. matches = [arch]
  833. if arch in ('i386', 'ppc'):
  834. matches.append('fat')
  835. if arch in ('i386', 'ppc', 'x86_64'):
  836. matches.append('fat3')
  837. if arch in ('ppc64', 'x86_64'):
  838. matches.append('fat64')
  839. if arch in ('i386', 'x86_64'):
  840. matches.append('intel')
  841. if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
  842. matches.append('universal')
  843. while minor >= 0:
  844. for match in matches:
  845. s = '%s_%s_%s_%s' % (name, major, minor, match)
  846. if s != ARCH: # already there
  847. arches.append(s)
  848. minor -= 1
  849. # Most specific - our Python version, ABI and arch
  850. for abi in abis:
  851. for arch in arches:
  852. result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
  853. # where no ABI / arch dependency, but IMP_PREFIX dependency
  854. for i, version in enumerate(versions):
  855. result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
  856. if i == 0:
  857. result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
  858. # no IMP_PREFIX, ABI or arch dependency
  859. for i, version in enumerate(versions):
  860. result.append((''.join(('py', version)), 'none', 'any'))
  861. if i == 0:
  862. result.append((''.join(('py', version[0])), 'none', 'any'))
  863. return set(result)
  864. COMPATIBLE_TAGS = compatible_tags()
  865. del compatible_tags
  866. def is_compatible(wheel, tags=None):
  867. if not isinstance(wheel, Wheel):
  868. wheel = Wheel(wheel) # assume it's a filename
  869. result = False
  870. if tags is None:
  871. tags = COMPATIBLE_TAGS
  872. for ver, abi, arch in tags:
  873. if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
  874. result = True
  875. break
  876. return result