wheel.py 43 KB

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