You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wheel.py 39KB

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