m2m模型翻译
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.

1099 lines
43 KiB

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