wheel.py 39 KB

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