wheel.py 43 KB

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