Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wheel.py 39KB

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