wheel.py 42 KB

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