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.

2025 lines
66 KiB

6 months ago
  1. #
  2. # Copyright (C) 2012-2023 The Python Software Foundation.
  3. # See LICENSE.txt and CONTRIBUTORS.txt.
  4. #
  5. import codecs
  6. from collections import deque
  7. import contextlib
  8. import csv
  9. from glob import iglob as std_iglob
  10. import io
  11. import json
  12. import logging
  13. import os
  14. import py_compile
  15. import re
  16. import socket
  17. try:
  18. import ssl
  19. except ImportError: # pragma: no cover
  20. ssl = None
  21. import subprocess
  22. import sys
  23. import tarfile
  24. import tempfile
  25. import textwrap
  26. try:
  27. import threading
  28. except ImportError: # pragma: no cover
  29. import dummy_threading as threading
  30. import time
  31. from . import DistlibException
  32. from .compat import (string_types, text_type, shutil, raw_input, StringIO,
  33. cache_from_source, urlopen, urljoin, httplib, xmlrpclib,
  34. HTTPHandler, BaseConfigurator, valid_ident,
  35. Container, configparser, URLError, ZipFile, fsdecode,
  36. unquote, urlparse)
  37. logger = logging.getLogger(__name__)
  38. #
  39. # Requirement parsing code as per PEP 508
  40. #
  41. IDENTIFIER = re.compile(r'^([\w\.-]+)\s*')
  42. VERSION_IDENTIFIER = re.compile(r'^([\w\.*+-]+)\s*')
  43. COMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\s*')
  44. MARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*')
  45. OR = re.compile(r'^or\b\s*')
  46. AND = re.compile(r'^and\b\s*')
  47. NON_SPACE = re.compile(r'(\S+)\s*')
  48. STRING_CHUNK = re.compile(r'([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)')
  49. def parse_marker(marker_string):
  50. """
  51. Parse a marker string and return a dictionary containing a marker expression.
  52. The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
  53. the expression grammar, or strings. A string contained in quotes is to be
  54. interpreted as a literal string, and a string not contained in quotes is a
  55. variable (such as os_name).
  56. """
  57. def marker_var(remaining):
  58. # either identifier, or literal string
  59. m = IDENTIFIER.match(remaining)
  60. if m:
  61. result = m.groups()[0]
  62. remaining = remaining[m.end():]
  63. elif not remaining:
  64. raise SyntaxError('unexpected end of input')
  65. else:
  66. q = remaining[0]
  67. if q not in '\'"':
  68. raise SyntaxError('invalid expression: %s' % remaining)
  69. oq = '\'"'.replace(q, '')
  70. remaining = remaining[1:]
  71. parts = [q]
  72. while remaining:
  73. # either a string chunk, or oq, or q to terminate
  74. if remaining[0] == q:
  75. break
  76. elif remaining[0] == oq:
  77. parts.append(oq)
  78. remaining = remaining[1:]
  79. else:
  80. m = STRING_CHUNK.match(remaining)
  81. if not m:
  82. raise SyntaxError('error in string literal: %s' %
  83. remaining)
  84. parts.append(m.groups()[0])
  85. remaining = remaining[m.end():]
  86. else:
  87. s = ''.join(parts)
  88. raise SyntaxError('unterminated string: %s' % s)
  89. parts.append(q)
  90. result = ''.join(parts)
  91. remaining = remaining[1:].lstrip() # skip past closing quote
  92. return result, remaining
  93. def marker_expr(remaining):
  94. if remaining and remaining[0] == '(':
  95. result, remaining = marker(remaining[1:].lstrip())
  96. if remaining[0] != ')':
  97. raise SyntaxError('unterminated parenthesis: %s' % remaining)
  98. remaining = remaining[1:].lstrip()
  99. else:
  100. lhs, remaining = marker_var(remaining)
  101. while remaining:
  102. m = MARKER_OP.match(remaining)
  103. if not m:
  104. break
  105. op = m.groups()[0]
  106. remaining = remaining[m.end():]
  107. rhs, remaining = marker_var(remaining)
  108. lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}
  109. result = lhs
  110. return result, remaining
  111. def marker_and(remaining):
  112. lhs, remaining = marker_expr(remaining)
  113. while remaining:
  114. m = AND.match(remaining)
  115. if not m:
  116. break
  117. remaining = remaining[m.end():]
  118. rhs, remaining = marker_expr(remaining)
  119. lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}
  120. return lhs, remaining
  121. def marker(remaining):
  122. lhs, remaining = marker_and(remaining)
  123. while remaining:
  124. m = OR.match(remaining)
  125. if not m:
  126. break
  127. remaining = remaining[m.end():]
  128. rhs, remaining = marker_and(remaining)
  129. lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}
  130. return lhs, remaining
  131. return marker(marker_string)
  132. def parse_requirement(req):
  133. """
  134. Parse a requirement passed in as a string. Return a Container
  135. whose attributes contain the various parts of the requirement.
  136. """
  137. remaining = req.strip()
  138. if not remaining or remaining.startswith('#'):
  139. return None
  140. m = IDENTIFIER.match(remaining)
  141. if not m:
  142. raise SyntaxError('name expected: %s' % remaining)
  143. distname = m.groups()[0]
  144. remaining = remaining[m.end():]
  145. extras = mark_expr = versions = uri = None
  146. if remaining and remaining[0] == '[':
  147. i = remaining.find(']', 1)
  148. if i < 0:
  149. raise SyntaxError('unterminated extra: %s' % remaining)
  150. s = remaining[1:i]
  151. remaining = remaining[i + 1:].lstrip()
  152. extras = []
  153. while s:
  154. m = IDENTIFIER.match(s)
  155. if not m:
  156. raise SyntaxError('malformed extra: %s' % s)
  157. extras.append(m.groups()[0])
  158. s = s[m.end():]
  159. if not s:
  160. break
  161. if s[0] != ',':
  162. raise SyntaxError('comma expected in extras: %s' % s)
  163. s = s[1:].lstrip()
  164. if not extras:
  165. extras = None
  166. if remaining:
  167. if remaining[0] == '@':
  168. # it's a URI
  169. remaining = remaining[1:].lstrip()
  170. m = NON_SPACE.match(remaining)
  171. if not m:
  172. raise SyntaxError('invalid URI: %s' % remaining)
  173. uri = m.groups()[0]
  174. t = urlparse(uri)
  175. # there are issues with Python and URL parsing, so this test
  176. # is a bit crude. See bpo-20271, bpo-23505. Python doesn't
  177. # always parse invalid URLs correctly - it should raise
  178. # exceptions for malformed URLs
  179. if not (t.scheme and t.netloc):
  180. raise SyntaxError('Invalid URL: %s' % uri)
  181. remaining = remaining[m.end():].lstrip()
  182. else:
  183. def get_versions(ver_remaining):
  184. """
  185. Return a list of operator, version tuples if any are
  186. specified, else None.
  187. """
  188. m = COMPARE_OP.match(ver_remaining)
  189. versions = None
  190. if m:
  191. versions = []
  192. while True:
  193. op = m.groups()[0]
  194. ver_remaining = ver_remaining[m.end():]
  195. m = VERSION_IDENTIFIER.match(ver_remaining)
  196. if not m:
  197. raise SyntaxError('invalid version: %s' %
  198. ver_remaining)
  199. v = m.groups()[0]
  200. versions.append((op, v))
  201. ver_remaining = ver_remaining[m.end():]
  202. if not ver_remaining or ver_remaining[0] != ',':
  203. break
  204. ver_remaining = ver_remaining[1:].lstrip()
  205. # Some packages have a trailing comma which would break things
  206. # See issue #148
  207. if not ver_remaining:
  208. break
  209. m = COMPARE_OP.match(ver_remaining)
  210. if not m:
  211. raise SyntaxError('invalid constraint: %s' %
  212. ver_remaining)
  213. if not versions:
  214. versions = None
  215. return versions, ver_remaining
  216. if remaining[0] != '(':
  217. versions, remaining = get_versions(remaining)
  218. else:
  219. i = remaining.find(')', 1)
  220. if i < 0:
  221. raise SyntaxError('unterminated parenthesis: %s' %
  222. remaining)
  223. s = remaining[1:i]
  224. remaining = remaining[i + 1:].lstrip()
  225. # As a special diversion from PEP 508, allow a version number
  226. # a.b.c in parentheses as a synonym for ~= a.b.c (because this
  227. # is allowed in earlier PEPs)
  228. if COMPARE_OP.match(s):
  229. versions, _ = get_versions(s)
  230. else:
  231. m = VERSION_IDENTIFIER.match(s)
  232. if not m:
  233. raise SyntaxError('invalid constraint: %s' % s)
  234. v = m.groups()[0]
  235. s = s[m.end():].lstrip()
  236. if s:
  237. raise SyntaxError('invalid constraint: %s' % s)
  238. versions = [('~=', v)]
  239. if remaining:
  240. if remaining[0] != ';':
  241. raise SyntaxError('invalid requirement: %s' % remaining)
  242. remaining = remaining[1:].lstrip()
  243. mark_expr, remaining = parse_marker(remaining)
  244. if remaining and remaining[0] != '#':
  245. raise SyntaxError('unexpected trailing data: %s' % remaining)
  246. if not versions:
  247. rs = distname
  248. else:
  249. rs = '%s %s' % (distname, ', '.join(
  250. ['%s %s' % con for con in versions]))
  251. return Container(name=distname,
  252. extras=extras,
  253. constraints=versions,
  254. marker=mark_expr,
  255. url=uri,
  256. requirement=rs)
  257. def get_resources_dests(resources_root, rules):
  258. """Find destinations for resources files"""
  259. def get_rel_path(root, path):
  260. # normalizes and returns a lstripped-/-separated path
  261. root = root.replace(os.path.sep, '/')
  262. path = path.replace(os.path.sep, '/')
  263. assert path.startswith(root)
  264. return path[len(root):].lstrip('/')
  265. destinations = {}
  266. for base, suffix, dest in rules:
  267. prefix = os.path.join(resources_root, base)
  268. for abs_base in iglob(prefix):
  269. abs_glob = os.path.join(abs_base, suffix)
  270. for abs_path in iglob(abs_glob):
  271. resource_file = get_rel_path(resources_root, abs_path)
  272. if dest is None: # remove the entry if it was here
  273. destinations.pop(resource_file, None)
  274. else:
  275. rel_path = get_rel_path(abs_base, abs_path)
  276. rel_dest = dest.replace(os.path.sep, '/').rstrip('/')
  277. destinations[resource_file] = rel_dest + '/' + rel_path
  278. return destinations
  279. def in_venv():
  280. if hasattr(sys, 'real_prefix'):
  281. # virtualenv venvs
  282. result = True
  283. else:
  284. # PEP 405 venvs
  285. result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)
  286. return result
  287. def get_executable():
  288. # The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as
  289. # changes to the stub launcher mean that sys.executable always points
  290. # to the stub on OS X
  291. # if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
  292. # in os.environ):
  293. # result = os.environ['__PYVENV_LAUNCHER__']
  294. # else:
  295. # result = sys.executable
  296. # return result
  297. # Avoid normcasing: see issue #143
  298. # result = os.path.normcase(sys.executable)
  299. result = sys.executable
  300. if not isinstance(result, text_type):
  301. result = fsdecode(result)
  302. return result
  303. def proceed(prompt, allowed_chars, error_prompt=None, default=None):
  304. p = prompt
  305. while True:
  306. s = raw_input(p)
  307. p = prompt
  308. if not s and default:
  309. s = default
  310. if s:
  311. c = s[0].lower()
  312. if c in allowed_chars:
  313. break
  314. if error_prompt:
  315. p = '%c: %s\n%s' % (c, error_prompt, prompt)
  316. return c
  317. def extract_by_key(d, keys):
  318. if isinstance(keys, string_types):
  319. keys = keys.split()
  320. result = {}
  321. for key in keys:
  322. if key in d:
  323. result[key] = d[key]
  324. return result
  325. def read_exports(stream):
  326. if sys.version_info[0] >= 3:
  327. # needs to be a text stream
  328. stream = codecs.getreader('utf-8')(stream)
  329. # Try to load as JSON, falling back on legacy format
  330. data = stream.read()
  331. stream = StringIO(data)
  332. try:
  333. jdata = json.load(stream)
  334. result = jdata['extensions']['python.exports']['exports']
  335. for group, entries in result.items():
  336. for k, v in entries.items():
  337. s = '%s = %s' % (k, v)
  338. entry = get_export_entry(s)
  339. assert entry is not None
  340. entries[k] = entry
  341. return result
  342. except Exception:
  343. stream.seek(0, 0)
  344. def read_stream(cp, stream):
  345. if hasattr(cp, 'read_file'):
  346. cp.read_file(stream)
  347. else:
  348. cp.readfp(stream)
  349. cp = configparser.ConfigParser()
  350. try:
  351. read_stream(cp, stream)
  352. except configparser.MissingSectionHeaderError:
  353. stream.close()
  354. data = textwrap.dedent(data)
  355. stream = StringIO(data)
  356. read_stream(cp, stream)
  357. result = {}
  358. for key in cp.sections():
  359. result[key] = entries = {}
  360. for name, value in cp.items(key):
  361. s = '%s = %s' % (name, value)
  362. entry = get_export_entry(s)
  363. assert entry is not None
  364. # entry.dist = self
  365. entries[name] = entry
  366. return result
  367. def write_exports(exports, stream):
  368. if sys.version_info[0] >= 3:
  369. # needs to be a text stream
  370. stream = codecs.getwriter('utf-8')(stream)
  371. cp = configparser.ConfigParser()
  372. for k, v in exports.items():
  373. # TODO check k, v for valid values
  374. cp.add_section(k)
  375. for entry in v.values():
  376. if entry.suffix is None:
  377. s = entry.prefix
  378. else:
  379. s = '%s:%s' % (entry.prefix, entry.suffix)
  380. if entry.flags:
  381. s = '%s [%s]' % (s, ', '.join(entry.flags))
  382. cp.set(k, entry.name, s)
  383. cp.write(stream)
  384. @contextlib.contextmanager
  385. def tempdir():
  386. td = tempfile.mkdtemp()
  387. try:
  388. yield td
  389. finally:
  390. shutil.rmtree(td)
  391. @contextlib.contextmanager
  392. def chdir(d):
  393. cwd = os.getcwd()
  394. try:
  395. os.chdir(d)
  396. yield
  397. finally:
  398. os.chdir(cwd)
  399. @contextlib.contextmanager
  400. def socket_timeout(seconds=15):
  401. cto = socket.getdefaulttimeout()
  402. try:
  403. socket.setdefaulttimeout(seconds)
  404. yield
  405. finally:
  406. socket.setdefaulttimeout(cto)
  407. class cached_property(object):
  408. def __init__(self, func):
  409. self.func = func
  410. # for attr in ('__name__', '__module__', '__doc__'):
  411. # setattr(self, attr, getattr(func, attr, None))
  412. def __get__(self, obj, cls=None):
  413. if obj is None:
  414. return self
  415. value = self.func(obj)
  416. object.__setattr__(obj, self.func.__name__, value)
  417. # obj.__dict__[self.func.__name__] = value = self.func(obj)
  418. return value
  419. def convert_path(pathname):
  420. """Return 'pathname' as a name that will work on the native filesystem.
  421. The path is split on '/' and put back together again using the current
  422. directory separator. Needed because filenames in the setup script are
  423. always supplied in Unix style, and have to be converted to the local
  424. convention before we can actually use them in the filesystem. Raises
  425. ValueError on non-Unix-ish systems if 'pathname' either starts or
  426. ends with a slash.
  427. """
  428. if os.sep == '/':
  429. return pathname
  430. if not pathname:
  431. return pathname
  432. if pathname[0] == '/':
  433. raise ValueError("path '%s' cannot be absolute" % pathname)
  434. if pathname[-1] == '/':
  435. raise ValueError("path '%s' cannot end with '/'" % pathname)
  436. paths = pathname.split('/')
  437. while os.curdir in paths:
  438. paths.remove(os.curdir)
  439. if not paths:
  440. return os.curdir
  441. return os.path.join(*paths)
  442. class FileOperator(object):
  443. def __init__(self, dry_run=False):
  444. self.dry_run = dry_run
  445. self.ensured = set()
  446. self._init_record()
  447. def _init_record(self):
  448. self.record = False
  449. self.files_written = set()
  450. self.dirs_created = set()
  451. def record_as_written(self, path):
  452. if self.record:
  453. self.files_written.add(path)
  454. def newer(self, source, target):
  455. """Tell if the target is newer than the source.
  456. Returns true if 'source' exists and is more recently modified than
  457. 'target', or if 'source' exists and 'target' doesn't.
  458. Returns false if both exist and 'target' is the same age or younger
  459. than 'source'. Raise PackagingFileError if 'source' does not exist.
  460. Note that this test is not very accurate: files created in the same
  461. second will have the same "age".
  462. """
  463. if not os.path.exists(source):
  464. raise DistlibException("file '%r' does not exist" %
  465. os.path.abspath(source))
  466. if not os.path.exists(target):
  467. return True
  468. return os.stat(source).st_mtime > os.stat(target).st_mtime
  469. def copy_file(self, infile, outfile, check=True):
  470. """Copy a file respecting dry-run and force flags.
  471. """
  472. self.ensure_dir(os.path.dirname(outfile))
  473. logger.info('Copying %s to %s', infile, outfile)
  474. if not self.dry_run:
  475. msg = None
  476. if check:
  477. if os.path.islink(outfile):
  478. msg = '%s is a symlink' % outfile
  479. elif os.path.exists(outfile) and not os.path.isfile(outfile):
  480. msg = '%s is a non-regular file' % outfile
  481. if msg:
  482. raise ValueError(msg + ' which would be overwritten')
  483. shutil.copyfile(infile, outfile)
  484. self.record_as_written(outfile)
  485. def copy_stream(self, instream, outfile, encoding=None):
  486. assert not os.path.isdir(outfile)
  487. self.ensure_dir(os.path.dirname(outfile))
  488. logger.info('Copying stream %s to %s', instream, outfile)
  489. if not self.dry_run:
  490. if encoding is None:
  491. outstream = open(outfile, 'wb')
  492. else:
  493. outstream = codecs.open(outfile, 'w', encoding=encoding)
  494. try:
  495. shutil.copyfileobj(instream, outstream)
  496. finally:
  497. outstream.close()
  498. self.record_as_written(outfile)
  499. def write_binary_file(self, path, data):
  500. self.ensure_dir(os.path.dirname(path))
  501. if not self.dry_run:
  502. if os.path.exists(path):
  503. os.remove(path)
  504. with open(path, 'wb') as f:
  505. f.write(data)
  506. self.record_as_written(path)
  507. def write_text_file(self, path, data, encoding):
  508. self.write_binary_file(path, data.encode(encoding))
  509. def set_mode(self, bits, mask, files):
  510. if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):
  511. # Set the executable bits (owner, group, and world) on
  512. # all the files specified.
  513. for f in files:
  514. if self.dry_run:
  515. logger.info("changing mode of %s", f)
  516. else:
  517. mode = (os.stat(f).st_mode | bits) & mask
  518. logger.info("changing mode of %s to %o", f, mode)
  519. os.chmod(f, mode)
  520. set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)
  521. def ensure_dir(self, path):
  522. path = os.path.abspath(path)
  523. if path not in self.ensured and not os.path.exists(path):
  524. self.ensured.add(path)
  525. d, f = os.path.split(path)
  526. self.ensure_dir(d)
  527. logger.info('Creating %s' % path)
  528. if not self.dry_run:
  529. os.mkdir(path)
  530. if self.record:
  531. self.dirs_created.add(path)
  532. def byte_compile(self,
  533. path,
  534. optimize=False,
  535. force=False,
  536. prefix=None,
  537. hashed_invalidation=False):
  538. dpath = cache_from_source(path, not optimize)
  539. logger.info('Byte-compiling %s to %s', path, dpath)
  540. if not self.dry_run:
  541. if force or self.newer(path, dpath):
  542. if not prefix:
  543. diagpath = None
  544. else:
  545. assert path.startswith(prefix)
  546. diagpath = path[len(prefix):]
  547. compile_kwargs = {}
  548. if hashed_invalidation and hasattr(py_compile,
  549. 'PycInvalidationMode'):
  550. compile_kwargs[
  551. 'invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH
  552. py_compile.compile(path, dpath, diagpath, True,
  553. **compile_kwargs) # raise error
  554. self.record_as_written(dpath)
  555. return dpath
  556. def ensure_removed(self, path):
  557. if os.path.exists(path):
  558. if os.path.isdir(path) and not os.path.islink(path):
  559. logger.debug('Removing directory tree at %s', path)
  560. if not self.dry_run:
  561. shutil.rmtree(path)
  562. if self.record:
  563. if path in self.dirs_created:
  564. self.dirs_created.remove(path)
  565. else:
  566. if os.path.islink(path):
  567. s = 'link'
  568. else:
  569. s = 'file'
  570. logger.debug('Removing %s %s', s, path)
  571. if not self.dry_run:
  572. os.remove(path)
  573. if self.record:
  574. if path in self.files_written:
  575. self.files_written.remove(path)
  576. def is_writable(self, path):
  577. result = False
  578. while not result:
  579. if os.path.exists(path):
  580. result = os.access(path, os.W_OK)
  581. break
  582. parent = os.path.dirname(path)
  583. if parent == path:
  584. break
  585. path = parent
  586. return result
  587. def commit(self):
  588. """
  589. Commit recorded changes, turn off recording, return
  590. changes.
  591. """
  592. assert self.record
  593. result = self.files_written, self.dirs_created
  594. self._init_record()
  595. return result
  596. def rollback(self):
  597. if not self.dry_run:
  598. for f in list(self.files_written):
  599. if os.path.exists(f):
  600. os.remove(f)
  601. # dirs should all be empty now, except perhaps for
  602. # __pycache__ subdirs
  603. # reverse so that subdirs appear before their parents
  604. dirs = sorted(self.dirs_created, reverse=True)
  605. for d in dirs:
  606. flist = os.listdir(d)
  607. if flist:
  608. assert flist == ['__pycache__']
  609. sd = os.path.join(d, flist[0])
  610. os.rmdir(sd)
  611. os.rmdir(d) # should fail if non-empty
  612. self._init_record()
  613. def resolve(module_name, dotted_path):
  614. if module_name in sys.modules:
  615. mod = sys.modules[module_name]
  616. else:
  617. mod = __import__(module_name)
  618. if dotted_path is None:
  619. result = mod
  620. else:
  621. parts = dotted_path.split('.')
  622. result = getattr(mod, parts.pop(0))
  623. for p in parts:
  624. result = getattr(result, p)
  625. return result
  626. class ExportEntry(object):
  627. def __init__(self, name, prefix, suffix, flags):
  628. self.name = name
  629. self.prefix = prefix
  630. self.suffix = suffix
  631. self.flags = flags
  632. @cached_property
  633. def value(self):
  634. return resolve(self.prefix, self.suffix)
  635. def __repr__(self): # pragma: no cover
  636. return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix,
  637. self.suffix, self.flags)
  638. def __eq__(self, other):
  639. if not isinstance(other, ExportEntry):
  640. result = False
  641. else:
  642. result = (self.name == other.name and self.prefix == other.prefix
  643. and self.suffix == other.suffix
  644. and self.flags == other.flags)
  645. return result
  646. __hash__ = object.__hash__
  647. ENTRY_RE = re.compile(
  648. r'''(?P<name>([^\[]\S*))
  649. \s*=\s*(?P<callable>(\w+)([:\.]\w+)*)
  650. \s*(\[\s*(?P<flags>[\w-]+(=\w+)?(,\s*\w+(=\w+)?)*)\s*\])?
  651. ''', re.VERBOSE)
  652. def get_export_entry(specification):
  653. m = ENTRY_RE.search(specification)
  654. if not m:
  655. result = None
  656. if '[' in specification or ']' in specification:
  657. raise DistlibException("Invalid specification "
  658. "'%s'" % specification)
  659. else:
  660. d = m.groupdict()
  661. name = d['name']
  662. path = d['callable']
  663. colons = path.count(':')
  664. if colons == 0:
  665. prefix, suffix = path, None
  666. else:
  667. if colons != 1:
  668. raise DistlibException("Invalid specification "
  669. "'%s'" % specification)
  670. prefix, suffix = path.split(':')
  671. flags = d['flags']
  672. if flags is None:
  673. if '[' in specification or ']' in specification:
  674. raise DistlibException("Invalid specification "
  675. "'%s'" % specification)
  676. flags = []
  677. else:
  678. flags = [f.strip() for f in flags.split(',')]
  679. result = ExportEntry(name, prefix, suffix, flags)
  680. return result
  681. def get_cache_base(suffix=None):
  682. """
  683. Return the default base location for distlib caches. If the directory does
  684. not exist, it is created. Use the suffix provided for the base directory,
  685. and default to '.distlib' if it isn't provided.
  686. On Windows, if LOCALAPPDATA is defined in the environment, then it is
  687. assumed to be a directory, and will be the parent directory of the result.
  688. On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
  689. directory - using os.expanduser('~') - will be the parent directory of
  690. the result.
  691. The result is just the directory '.distlib' in the parent directory as
  692. determined above, or with the name specified with ``suffix``.
  693. """
  694. if suffix is None:
  695. suffix = '.distlib'
  696. if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
  697. result = os.path.expandvars('$localappdata')
  698. else:
  699. # Assume posix, or old Windows
  700. result = os.path.expanduser('~')
  701. # we use 'isdir' instead of 'exists', because we want to
  702. # fail if there's a file with that name
  703. if os.path.isdir(result):
  704. usable = os.access(result, os.W_OK)
  705. if not usable:
  706. logger.warning('Directory exists but is not writable: %s', result)
  707. else:
  708. try:
  709. os.makedirs(result)
  710. usable = True
  711. except OSError:
  712. logger.warning('Unable to create %s', result, exc_info=True)
  713. usable = False
  714. if not usable:
  715. result = tempfile.mkdtemp()
  716. logger.warning('Default location unusable, using %s', result)
  717. return os.path.join(result, suffix)
  718. def path_to_cache_dir(path):
  719. """
  720. Convert an absolute path to a directory name for use in a cache.
  721. The algorithm used is:
  722. #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.
  723. #. Any occurrence of ``os.sep`` is replaced with ``'--'``.
  724. #. ``'.cache'`` is appended.
  725. """
  726. d, p = os.path.splitdrive(os.path.abspath(path))
  727. if d:
  728. d = d.replace(':', '---')
  729. p = p.replace(os.sep, '--')
  730. return d + p + '.cache'
  731. def ensure_slash(s):
  732. if not s.endswith('/'):
  733. return s + '/'
  734. return s
  735. def parse_credentials(netloc):
  736. username = password = None
  737. if '@' in netloc:
  738. prefix, netloc = netloc.rsplit('@', 1)
  739. if ':' not in prefix:
  740. username = prefix
  741. else:
  742. username, password = prefix.split(':', 1)
  743. if username:
  744. username = unquote(username)
  745. if password:
  746. password = unquote(password)
  747. return username, password, netloc
  748. def get_process_umask():
  749. result = os.umask(0o22)
  750. os.umask(result)
  751. return result
  752. def is_string_sequence(seq):
  753. result = True
  754. i = None
  755. for i, s in enumerate(seq):
  756. if not isinstance(s, string_types):
  757. result = False
  758. break
  759. assert i is not None
  760. return result
  761. PROJECT_NAME_AND_VERSION = re.compile(
  762. '([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'
  763. '([a-z0-9_.+-]+)', re.I)
  764. PYTHON_VERSION = re.compile(r'-py(\d\.?\d?)')
  765. def split_filename(filename, project_name=None):
  766. """
  767. Extract name, version, python version from a filename (no extension)
  768. Return name, version, pyver or None
  769. """
  770. result = None
  771. pyver = None
  772. filename = unquote(filename).replace(' ', '-')
  773. m = PYTHON_VERSION.search(filename)
  774. if m:
  775. pyver = m.group(1)
  776. filename = filename[:m.start()]
  777. if project_name and len(filename) > len(project_name) + 1:
  778. m = re.match(re.escape(project_name) + r'\b', filename)
  779. if m:
  780. n = m.end()
  781. result = filename[:n], filename[n + 1:], pyver
  782. if result is None:
  783. m = PROJECT_NAME_AND_VERSION.match(filename)
  784. if m:
  785. result = m.group(1), m.group(3), pyver
  786. return result
  787. # Allow spaces in name because of legacy dists like "Twisted Core"
  788. NAME_VERSION_RE = re.compile(r'(?P<name>[\w .-]+)\s*'
  789. r'\(\s*(?P<ver>[^\s)]+)\)$')
  790. def parse_name_and_version(p):
  791. """
  792. A utility method used to get name and version from a string.
  793. From e.g. a Provides-Dist value.
  794. :param p: A value in a form 'foo (1.0)'
  795. :return: The name and version as a tuple.
  796. """
  797. m = NAME_VERSION_RE.match(p)
  798. if not m:
  799. raise DistlibException('Ill-formed name/version string: \'%s\'' % p)
  800. d = m.groupdict()
  801. return d['name'].strip().lower(), d['ver']
  802. def get_extras(requested, available):
  803. result = set()
  804. requested = set(requested or [])
  805. available = set(available or [])
  806. if '*' in requested:
  807. requested.remove('*')
  808. result |= available
  809. for r in requested:
  810. if r == '-':
  811. result.add(r)
  812. elif r.startswith('-'):
  813. unwanted = r[1:]
  814. if unwanted not in available:
  815. logger.warning('undeclared extra: %s' % unwanted)
  816. if unwanted in result:
  817. result.remove(unwanted)
  818. else:
  819. if r not in available:
  820. logger.warning('undeclared extra: %s' % r)
  821. result.add(r)
  822. return result
  823. #
  824. # Extended metadata functionality
  825. #
  826. def _get_external_data(url):
  827. result = {}
  828. try:
  829. # urlopen might fail if it runs into redirections,
  830. # because of Python issue #13696. Fixed in locators
  831. # using a custom redirect handler.
  832. resp = urlopen(url)
  833. headers = resp.info()
  834. ct = headers.get('Content-Type')
  835. if not ct.startswith('application/json'):
  836. logger.debug('Unexpected response for JSON request: %s', ct)
  837. else:
  838. reader = codecs.getreader('utf-8')(resp)
  839. # data = reader.read().decode('utf-8')
  840. # result = json.loads(data)
  841. result = json.load(reader)
  842. except Exception as e:
  843. logger.exception('Failed to get external data for %s: %s', url, e)
  844. return result
  845. _external_data_base_url = 'https://www.red-dove.com/pypi/projects/'
  846. def get_project_data(name):
  847. url = '%s/%s/project.json' % (name[0].upper(), name)
  848. url = urljoin(_external_data_base_url, url)
  849. result = _get_external_data(url)
  850. return result
  851. def get_package_data(name, version):
  852. url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)
  853. url = urljoin(_external_data_base_url, url)
  854. return _get_external_data(url)
  855. class Cache(object):
  856. """
  857. A class implementing a cache for resources that need to live in the file system
  858. e.g. shared libraries. This class was moved from resources to here because it
  859. could be used by other modules, e.g. the wheel module.
  860. """
  861. def __init__(self, base):
  862. """
  863. Initialise an instance.
  864. :param base: The base directory where the cache should be located.
  865. """
  866. # we use 'isdir' instead of 'exists', because we want to
  867. # fail if there's a file with that name
  868. if not os.path.isdir(base): # pragma: no cover
  869. os.makedirs(base)
  870. if (os.stat(base).st_mode & 0o77) != 0:
  871. logger.warning('Directory \'%s\' is not private', base)
  872. self.base = os.path.abspath(os.path.normpath(base))
  873. def prefix_to_dir(self, prefix):
  874. """
  875. Converts a resource prefix to a directory name in the cache.
  876. """
  877. return path_to_cache_dir(prefix)
  878. def clear(self):
  879. """
  880. Clear the cache.
  881. """
  882. not_removed = []
  883. for fn in os.listdir(self.base):
  884. fn = os.path.join(self.base, fn)
  885. try:
  886. if os.path.islink(fn) or os.path.isfile(fn):
  887. os.remove(fn)
  888. elif os.path.isdir(fn):
  889. shutil.rmtree(fn)
  890. except Exception:
  891. not_removed.append(fn)
  892. return not_removed
  893. class EventMixin(object):
  894. """
  895. A very simple publish/subscribe system.
  896. """
  897. def __init__(self):
  898. self._subscribers = {}
  899. def add(self, event, subscriber, append=True):
  900. """
  901. Add a subscriber for an event.
  902. :param event: The name of an event.
  903. :param subscriber: The subscriber to be added (and called when the
  904. event is published).
  905. :param append: Whether to append or prepend the subscriber to an
  906. existing subscriber list for the event.
  907. """
  908. subs = self._subscribers
  909. if event not in subs:
  910. subs[event] = deque([subscriber])
  911. else:
  912. sq = subs[event]
  913. if append:
  914. sq.append(subscriber)
  915. else:
  916. sq.appendleft(subscriber)
  917. def remove(self, event, subscriber):
  918. """
  919. Remove a subscriber for an event.
  920. :param event: The name of an event.
  921. :param subscriber: The subscriber to be removed.
  922. """
  923. subs = self._subscribers
  924. if event not in subs:
  925. raise ValueError('No subscribers: %r' % event)
  926. subs[event].remove(subscriber)
  927. def get_subscribers(self, event):
  928. """
  929. Return an iterator for the subscribers for an event.
  930. :param event: The event to return subscribers for.
  931. """
  932. return iter(self._subscribers.get(event, ()))
  933. def publish(self, event, *args, **kwargs):
  934. """
  935. Publish a event and return a list of values returned by its
  936. subscribers.
  937. :param event: The event to publish.
  938. :param args: The positional arguments to pass to the event's
  939. subscribers.
  940. :param kwargs: The keyword arguments to pass to the event's
  941. subscribers.
  942. """
  943. result = []
  944. for subscriber in self.get_subscribers(event):
  945. try:
  946. value = subscriber(event, *args, **kwargs)
  947. except Exception:
  948. logger.exception('Exception during event publication')
  949. value = None
  950. result.append(value)
  951. logger.debug('publish %s: args = %s, kwargs = %s, result = %s', event,
  952. args, kwargs, result)
  953. return result
  954. #
  955. # Simple sequencing
  956. #
  957. class Sequencer(object):
  958. def __init__(self):
  959. self._preds = {}
  960. self._succs = {}
  961. self._nodes = set() # nodes with no preds/succs
  962. def add_node(self, node):
  963. self._nodes.add(node)
  964. def remove_node(self, node, edges=False):
  965. if node in self._nodes:
  966. self._nodes.remove(node)
  967. if edges:
  968. for p in set(self._preds.get(node, ())):
  969. self.remove(p, node)
  970. for s in set(self._succs.get(node, ())):
  971. self.remove(node, s)
  972. # Remove empties
  973. for k, v in list(self._preds.items()):
  974. if not v:
  975. del self._preds[k]
  976. for k, v in list(self._succs.items()):
  977. if not v:
  978. del self._succs[k]
  979. def add(self, pred, succ):
  980. assert pred != succ
  981. self._preds.setdefault(succ, set()).add(pred)
  982. self._succs.setdefault(pred, set()).add(succ)
  983. def remove(self, pred, succ):
  984. assert pred != succ
  985. try:
  986. preds = self._preds[succ]
  987. succs = self._succs[pred]
  988. except KeyError: # pragma: no cover
  989. raise ValueError('%r not a successor of anything' % succ)
  990. try:
  991. preds.remove(pred)
  992. succs.remove(succ)
  993. except KeyError: # pragma: no cover
  994. raise ValueError('%r not a successor of %r' % (succ, pred))
  995. def is_step(self, step):
  996. return (step in self._preds or step in self._succs
  997. or step in self._nodes)
  998. def get_steps(self, final):
  999. if not self.is_step(final):
  1000. raise ValueError('Unknown: %r' % final)
  1001. result = []
  1002. todo = []
  1003. seen = set()
  1004. todo.append(final)
  1005. while todo:
  1006. step = todo.pop(0)
  1007. if step in seen:
  1008. # if a step was already seen,
  1009. # move it to the end (so it will appear earlier
  1010. # when reversed on return) ... but not for the
  1011. # final step, as that would be confusing for
  1012. # users
  1013. if step != final:
  1014. result.remove(step)
  1015. result.append(step)
  1016. else:
  1017. seen.add(step)
  1018. result.append(step)
  1019. preds = self._preds.get(step, ())
  1020. todo.extend(preds)
  1021. return reversed(result)
  1022. @property
  1023. def strong_connections(self):
  1024. # http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
  1025. index_counter = [0]
  1026. stack = []
  1027. lowlinks = {}
  1028. index = {}
  1029. result = []
  1030. graph = self._succs
  1031. def strongconnect(node):
  1032. # set the depth index for this node to the smallest unused index
  1033. index[node] = index_counter[0]
  1034. lowlinks[node] = index_counter[0]
  1035. index_counter[0] += 1
  1036. stack.append(node)
  1037. # Consider successors
  1038. try:
  1039. successors = graph[node]
  1040. except Exception:
  1041. successors = []
  1042. for successor in successors:
  1043. if successor not in lowlinks:
  1044. # Successor has not yet been visited
  1045. strongconnect(successor)
  1046. lowlinks[node] = min(lowlinks[node], lowlinks[successor])
  1047. elif successor in stack:
  1048. # the successor is in the stack and hence in the current
  1049. # strongly connected component (SCC)
  1050. lowlinks[node] = min(lowlinks[node], index[successor])
  1051. # If `node` is a root node, pop the stack and generate an SCC
  1052. if lowlinks[node] == index[node]:
  1053. connected_component = []
  1054. while True:
  1055. successor = stack.pop()
  1056. connected_component.append(successor)
  1057. if successor == node:
  1058. break
  1059. component = tuple(connected_component)
  1060. # storing the result
  1061. result.append(component)
  1062. for node in graph:
  1063. if node not in lowlinks:
  1064. strongconnect(node)
  1065. return result
  1066. @property
  1067. def dot(self):
  1068. result = ['digraph G {']
  1069. for succ in self._preds:
  1070. preds = self._preds[succ]
  1071. for pred in preds:
  1072. result.append(' %s -> %s;' % (pred, succ))
  1073. for node in self._nodes:
  1074. result.append(' %s;' % node)
  1075. result.append('}')
  1076. return '\n'.join(result)
  1077. #
  1078. # Unarchiving functionality for zip, tar, tgz, tbz, whl
  1079. #
  1080. ARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz',
  1081. '.whl')
  1082. def unarchive(archive_filename, dest_dir, format=None, check=True):
  1083. def check_path(path):
  1084. if not isinstance(path, text_type):
  1085. path = path.decode('utf-8')
  1086. p = os.path.abspath(os.path.join(dest_dir, path))
  1087. if not p.startswith(dest_dir) or p[plen] != os.sep:
  1088. raise ValueError('path outside destination: %r' % p)
  1089. dest_dir = os.path.abspath(dest_dir)
  1090. plen = len(dest_dir)
  1091. archive = None
  1092. if format is None:
  1093. if archive_filename.endswith(('.zip', '.whl')):
  1094. format = 'zip'
  1095. elif archive_filename.endswith(('.tar.gz', '.tgz')):
  1096. format = 'tgz'
  1097. mode = 'r:gz'
  1098. elif archive_filename.endswith(('.tar.bz2', '.tbz')):
  1099. format = 'tbz'
  1100. mode = 'r:bz2'
  1101. elif archive_filename.endswith('.tar'):
  1102. format = 'tar'
  1103. mode = 'r'
  1104. else: # pragma: no cover
  1105. raise ValueError('Unknown format for %r' % archive_filename)
  1106. try:
  1107. if format == 'zip':
  1108. archive = ZipFile(archive_filename, 'r')
  1109. if check:
  1110. names = archive.namelist()
  1111. for name in names:
  1112. check_path(name)
  1113. else:
  1114. archive = tarfile.open(archive_filename, mode)
  1115. if check:
  1116. names = archive.getnames()
  1117. for name in names:
  1118. check_path(name)
  1119. if format != 'zip' and sys.version_info[0] < 3:
  1120. # See Python issue 17153. If the dest path contains Unicode,
  1121. # tarfile extraction fails on Python 2.x if a member path name
  1122. # contains non-ASCII characters - it leads to an implicit
  1123. # bytes -> unicode conversion using ASCII to decode.
  1124. for tarinfo in archive.getmembers():
  1125. if not isinstance(tarinfo.name, text_type):
  1126. tarinfo.name = tarinfo.name.decode('utf-8')
  1127. # Limit extraction of dangerous items, if this Python
  1128. # allows it easily. If not, just trust the input.
  1129. # See: https://docs.python.org/3/library/tarfile.html#extraction-filters
  1130. def extraction_filter(member, path):
  1131. """Run tarfile.tar_filter, but raise the expected ValueError"""
  1132. # This is only called if the current Python has tarfile filters
  1133. try:
  1134. return tarfile.tar_filter(member, path)
  1135. except tarfile.FilterError as exc:
  1136. raise ValueError(str(exc))
  1137. archive.extraction_filter = extraction_filter
  1138. archive.extractall(dest_dir)
  1139. finally:
  1140. if archive:
  1141. archive.close()
  1142. def zip_dir(directory):
  1143. """zip a directory tree into a BytesIO object"""
  1144. result = io.BytesIO()
  1145. dlen = len(directory)
  1146. with ZipFile(result, "w") as zf:
  1147. for root, dirs, files in os.walk(directory):
  1148. for name in files:
  1149. full = os.path.join(root, name)
  1150. rel = root[dlen:]
  1151. dest = os.path.join(rel, name)
  1152. zf.write(full, dest)
  1153. return result
  1154. #
  1155. # Simple progress bar
  1156. #
  1157. UNITS = ('', 'K', 'M', 'G', 'T', 'P')
  1158. class Progress(object):
  1159. unknown = 'UNKNOWN'
  1160. def __init__(self, minval=0, maxval=100):
  1161. assert maxval is None or maxval >= minval
  1162. self.min = self.cur = minval
  1163. self.max = maxval
  1164. self.started = None
  1165. self.elapsed = 0
  1166. self.done = False
  1167. def update(self, curval):
  1168. assert self.min <= curval
  1169. assert self.max is None or curval <= self.max
  1170. self.cur = curval
  1171. now = time.time()
  1172. if self.started is None:
  1173. self.started = now
  1174. else:
  1175. self.elapsed = now - self.started
  1176. def increment(self, incr):
  1177. assert incr >= 0
  1178. self.update(self.cur + incr)
  1179. def start(self):
  1180. self.update(self.min)
  1181. return self
  1182. def stop(self):
  1183. if self.max is not None:
  1184. self.update(self.max)
  1185. self.done = True
  1186. @property
  1187. def maximum(self):
  1188. return self.unknown if self.max is None else self.max
  1189. @property
  1190. def percentage(self):
  1191. if self.done:
  1192. result = '100 %'
  1193. elif self.max is None:
  1194. result = ' ?? %'
  1195. else:
  1196. v = 100.0 * (self.cur - self.min) / (self.max - self.min)
  1197. result = '%3d %%' % v
  1198. return result
  1199. def format_duration(self, duration):
  1200. if (duration <= 0) and self.max is None or self.cur == self.min:
  1201. result = '??:??:??'
  1202. # elif duration < 1:
  1203. # result = '--:--:--'
  1204. else:
  1205. result = time.strftime('%H:%M:%S', time.gmtime(duration))
  1206. return result
  1207. @property
  1208. def ETA(self):
  1209. if self.done:
  1210. prefix = 'Done'
  1211. t = self.elapsed
  1212. # import pdb; pdb.set_trace()
  1213. else:
  1214. prefix = 'ETA '
  1215. if self.max is None:
  1216. t = -1
  1217. elif self.elapsed == 0 or (self.cur == self.min):
  1218. t = 0
  1219. else:
  1220. # import pdb; pdb.set_trace()
  1221. t = float(self.max - self.min)
  1222. t /= self.cur - self.min
  1223. t = (t - 1) * self.elapsed
  1224. return '%s: %s' % (prefix, self.format_duration(t))
  1225. @property
  1226. def speed(self):
  1227. if self.elapsed == 0:
  1228. result = 0.0
  1229. else:
  1230. result = (self.cur - self.min) / self.elapsed
  1231. for unit in UNITS:
  1232. if result < 1000:
  1233. break
  1234. result /= 1000.0
  1235. return '%d %sB/s' % (result, unit)
  1236. #
  1237. # Glob functionality
  1238. #
  1239. RICH_GLOB = re.compile(r'\{([^}]*)\}')
  1240. _CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\,{]\*\*|\*\*[^/\\,}]')
  1241. _CHECK_MISMATCH_SET = re.compile(r'^[^{]*\}|\{[^}]*$')
  1242. def iglob(path_glob):
  1243. """Extended globbing function that supports ** and {opt1,opt2,opt3}."""
  1244. if _CHECK_RECURSIVE_GLOB.search(path_glob):
  1245. msg = """invalid glob %r: recursive glob "**" must be used alone"""
  1246. raise ValueError(msg % path_glob)
  1247. if _CHECK_MISMATCH_SET.search(path_glob):
  1248. msg = """invalid glob %r: mismatching set marker '{' or '}'"""
  1249. raise ValueError(msg % path_glob)
  1250. return _iglob(path_glob)
  1251. def _iglob(path_glob):
  1252. rich_path_glob = RICH_GLOB.split(path_glob, 1)
  1253. if len(rich_path_glob) > 1:
  1254. assert len(rich_path_glob) == 3, rich_path_glob
  1255. prefix, set, suffix = rich_path_glob
  1256. for item in set.split(','):
  1257. for path in _iglob(''.join((prefix, item, suffix))):
  1258. yield path
  1259. else:
  1260. if '**' not in path_glob:
  1261. for item in std_iglob(path_glob):
  1262. yield item
  1263. else:
  1264. prefix, radical = path_glob.split('**', 1)
  1265. if prefix == '':
  1266. prefix = '.'
  1267. if radical == '':
  1268. radical = '*'
  1269. else:
  1270. # we support both
  1271. radical = radical.lstrip('/')
  1272. radical = radical.lstrip('\\')
  1273. for path, dir, files in os.walk(prefix):
  1274. path = os.path.normpath(path)
  1275. for fn in _iglob(os.path.join(path, radical)):
  1276. yield fn
  1277. if ssl:
  1278. from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname,
  1279. CertificateError)
  1280. #
  1281. # HTTPSConnection which verifies certificates/matches domains
  1282. #
  1283. class HTTPSConnection(httplib.HTTPSConnection):
  1284. ca_certs = None # set this to the path to the certs file (.pem)
  1285. check_domain = True # only used if ca_certs is not None
  1286. # noinspection PyPropertyAccess
  1287. def connect(self):
  1288. sock = socket.create_connection((self.host, self.port),
  1289. self.timeout)
  1290. if getattr(self, '_tunnel_host', False):
  1291. self.sock = sock
  1292. self._tunnel()
  1293. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  1294. if hasattr(ssl, 'OP_NO_SSLv2'):
  1295. context.options |= ssl.OP_NO_SSLv2
  1296. if getattr(self, 'cert_file', None):
  1297. context.load_cert_chain(self.cert_file, self.key_file)
  1298. kwargs = {}
  1299. if self.ca_certs:
  1300. context.verify_mode = ssl.CERT_REQUIRED
  1301. context.load_verify_locations(cafile=self.ca_certs)
  1302. if getattr(ssl, 'HAS_SNI', False):
  1303. kwargs['server_hostname'] = self.host
  1304. self.sock = context.wrap_socket(sock, **kwargs)
  1305. if self.ca_certs and self.check_domain:
  1306. try:
  1307. match_hostname(self.sock.getpeercert(), self.host)
  1308. logger.debug('Host verified: %s', self.host)
  1309. except CertificateError: # pragma: no cover
  1310. self.sock.shutdown(socket.SHUT_RDWR)
  1311. self.sock.close()
  1312. raise
  1313. class HTTPSHandler(BaseHTTPSHandler):
  1314. def __init__(self, ca_certs, check_domain=True):
  1315. BaseHTTPSHandler.__init__(self)
  1316. self.ca_certs = ca_certs
  1317. self.check_domain = check_domain
  1318. def _conn_maker(self, *args, **kwargs):
  1319. """
  1320. This is called to create a connection instance. Normally you'd
  1321. pass a connection class to do_open, but it doesn't actually check for
  1322. a class, and just expects a callable. As long as we behave just as a
  1323. constructor would have, we should be OK. If it ever changes so that
  1324. we *must* pass a class, we'll create an UnsafeHTTPSConnection class
  1325. which just sets check_domain to False in the class definition, and
  1326. choose which one to pass to do_open.
  1327. """
  1328. result = HTTPSConnection(*args, **kwargs)
  1329. if self.ca_certs:
  1330. result.ca_certs = self.ca_certs
  1331. result.check_domain = self.check_domain
  1332. return result
  1333. def https_open(self, req):
  1334. try:
  1335. return self.do_open(self._conn_maker, req)
  1336. except URLError as e:
  1337. if 'certificate verify failed' in str(e.reason):
  1338. raise CertificateError(
  1339. 'Unable to verify server certificate '
  1340. 'for %s' % req.host)
  1341. else:
  1342. raise
  1343. #
  1344. # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-
  1345. # Middle proxy using HTTP listens on port 443, or an index mistakenly serves
  1346. # HTML containing a http://xyz link when it should be https://xyz),
  1347. # you can use the following handler class, which does not allow HTTP traffic.
  1348. #
  1349. # It works by inheriting from HTTPHandler - so build_opener won't add a
  1350. # handler for HTTP itself.
  1351. #
  1352. class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):
  1353. def http_open(self, req):
  1354. raise URLError(
  1355. 'Unexpected HTTP request on what should be a secure '
  1356. 'connection: %s' % req)
  1357. #
  1358. # XML-RPC with timeouts
  1359. #
  1360. class Transport(xmlrpclib.Transport):
  1361. def __init__(self, timeout, use_datetime=0):
  1362. self.timeout = timeout
  1363. xmlrpclib.Transport.__init__(self, use_datetime)
  1364. def make_connection(self, host):
  1365. h, eh, x509 = self.get_host_info(host)
  1366. if not self._connection or host != self._connection[0]:
  1367. self._extra_headers = eh
  1368. self._connection = host, httplib.HTTPConnection(h)
  1369. return self._connection[1]
  1370. if ssl:
  1371. class SafeTransport(xmlrpclib.SafeTransport):
  1372. def __init__(self, timeout, use_datetime=0):
  1373. self.timeout = timeout
  1374. xmlrpclib.SafeTransport.__init__(self, use_datetime)
  1375. def make_connection(self, host):
  1376. h, eh, kwargs = self.get_host_info(host)
  1377. if not kwargs:
  1378. kwargs = {}
  1379. kwargs['timeout'] = self.timeout
  1380. if not self._connection or host != self._connection[0]:
  1381. self._extra_headers = eh
  1382. self._connection = host, httplib.HTTPSConnection(
  1383. h, None, **kwargs)
  1384. return self._connection[1]
  1385. class ServerProxy(xmlrpclib.ServerProxy):
  1386. def __init__(self, uri, **kwargs):
  1387. self.timeout = timeout = kwargs.pop('timeout', None)
  1388. # The above classes only come into play if a timeout
  1389. # is specified
  1390. if timeout is not None:
  1391. # scheme = splittype(uri) # deprecated as of Python 3.8
  1392. scheme = urlparse(uri)[0]
  1393. use_datetime = kwargs.get('use_datetime', 0)
  1394. if scheme == 'https':
  1395. tcls = SafeTransport
  1396. else:
  1397. tcls = Transport
  1398. kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)
  1399. self.transport = t
  1400. xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)
  1401. #
  1402. # CSV functionality. This is provided because on 2.x, the csv module can't
  1403. # handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.
  1404. #
  1405. def _csv_open(fn, mode, **kwargs):
  1406. if sys.version_info[0] < 3:
  1407. mode += 'b'
  1408. else:
  1409. kwargs['newline'] = ''
  1410. # Python 3 determines encoding from locale. Force 'utf-8'
  1411. # file encoding to match other forced utf-8 encoding
  1412. kwargs['encoding'] = 'utf-8'
  1413. return open(fn, mode, **kwargs)
  1414. class CSVBase(object):
  1415. defaults = {
  1416. 'delimiter': str(','), # The strs are used because we need native
  1417. 'quotechar': str('"'), # str in the csv API (2.x won't take
  1418. 'lineterminator': str('\n') # Unicode)
  1419. }
  1420. def __enter__(self):
  1421. return self
  1422. def __exit__(self, *exc_info):
  1423. self.stream.close()
  1424. class CSVReader(CSVBase):
  1425. def __init__(self, **kwargs):
  1426. if 'stream' in kwargs:
  1427. stream = kwargs['stream']
  1428. if sys.version_info[0] >= 3:
  1429. # needs to be a text stream
  1430. stream = codecs.getreader('utf-8')(stream)
  1431. self.stream = stream
  1432. else:
  1433. self.stream = _csv_open(kwargs['path'], 'r')
  1434. self.reader = csv.reader(self.stream, **self.defaults)
  1435. def __iter__(self):
  1436. return self
  1437. def next(self):
  1438. result = next(self.reader)
  1439. if sys.version_info[0] < 3:
  1440. for i, item in enumerate(result):
  1441. if not isinstance(item, text_type):
  1442. result[i] = item.decode('utf-8')
  1443. return result
  1444. __next__ = next
  1445. class CSVWriter(CSVBase):
  1446. def __init__(self, fn, **kwargs):
  1447. self.stream = _csv_open(fn, 'w')
  1448. self.writer = csv.writer(self.stream, **self.defaults)
  1449. def writerow(self, row):
  1450. if sys.version_info[0] < 3:
  1451. r = []
  1452. for item in row:
  1453. if isinstance(item, text_type):
  1454. item = item.encode('utf-8')
  1455. r.append(item)
  1456. row = r
  1457. self.writer.writerow(row)
  1458. #
  1459. # Configurator functionality
  1460. #
  1461. class Configurator(BaseConfigurator):
  1462. value_converters = dict(BaseConfigurator.value_converters)
  1463. value_converters['inc'] = 'inc_convert'
  1464. def __init__(self, config, base=None):
  1465. super(Configurator, self).__init__(config)
  1466. self.base = base or os.getcwd()
  1467. def configure_custom(self, config):
  1468. def convert(o):
  1469. if isinstance(o, (list, tuple)):
  1470. result = type(o)([convert(i) for i in o])
  1471. elif isinstance(o, dict):
  1472. if '()' in o:
  1473. result = self.configure_custom(o)
  1474. else:
  1475. result = {}
  1476. for k in o:
  1477. result[k] = convert(o[k])
  1478. else:
  1479. result = self.convert(o)
  1480. return result
  1481. c = config.pop('()')
  1482. if not callable(c):
  1483. c = self.resolve(c)
  1484. props = config.pop('.', None)
  1485. # Check for valid identifiers
  1486. args = config.pop('[]', ())
  1487. if args:
  1488. args = tuple([convert(o) for o in args])
  1489. items = [(k, convert(config[k])) for k in config if valid_ident(k)]
  1490. kwargs = dict(items)
  1491. result = c(*args, **kwargs)
  1492. if props:
  1493. for n, v in props.items():
  1494. setattr(result, n, convert(v))
  1495. return result
  1496. def __getitem__(self, key):
  1497. result = self.config[key]
  1498. if isinstance(result, dict) and '()' in result:
  1499. self.config[key] = result = self.configure_custom(result)
  1500. return result
  1501. def inc_convert(self, value):
  1502. """Default converter for the inc:// protocol."""
  1503. if not os.path.isabs(value):
  1504. value = os.path.join(self.base, value)
  1505. with codecs.open(value, 'r', encoding='utf-8') as f:
  1506. result = json.load(f)
  1507. return result
  1508. class SubprocessMixin(object):
  1509. """
  1510. Mixin for running subprocesses and capturing their output
  1511. """
  1512. def __init__(self, verbose=False, progress=None):
  1513. self.verbose = verbose
  1514. self.progress = progress
  1515. def reader(self, stream, context):
  1516. """
  1517. Read lines from a subprocess' output stream and either pass to a progress
  1518. callable (if specified) or write progress information to sys.stderr.
  1519. """
  1520. progress = self.progress
  1521. verbose = self.verbose
  1522. while True:
  1523. s = stream.readline()
  1524. if not s:
  1525. break
  1526. if progress is not None:
  1527. progress(s, context)
  1528. else:
  1529. if not verbose:
  1530. sys.stderr.write('.')
  1531. else:
  1532. sys.stderr.write(s.decode('utf-8'))
  1533. sys.stderr.flush()
  1534. stream.close()
  1535. def run_command(self, cmd, **kwargs):
  1536. p = subprocess.Popen(cmd,
  1537. stdout=subprocess.PIPE,
  1538. stderr=subprocess.PIPE,
  1539. **kwargs)
  1540. t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))
  1541. t1.start()
  1542. t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))
  1543. t2.start()
  1544. p.wait()
  1545. t1.join()
  1546. t2.join()
  1547. if self.progress is not None:
  1548. self.progress('done.', 'main')
  1549. elif self.verbose:
  1550. sys.stderr.write('done.\n')
  1551. return p
  1552. def normalize_name(name):
  1553. """Normalize a python package name a la PEP 503"""
  1554. # https://www.python.org/dev/peps/pep-0503/#normalized-names
  1555. return re.sub('[-_.]+', '-', name).lower()
  1556. # def _get_pypirc_command():
  1557. # """
  1558. # Get the distutils command for interacting with PyPI configurations.
  1559. # :return: the command.
  1560. # """
  1561. # from distutils.core import Distribution
  1562. # from distutils.config import PyPIRCCommand
  1563. # d = Distribution()
  1564. # return PyPIRCCommand(d)
  1565. class PyPIRCFile(object):
  1566. DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
  1567. DEFAULT_REALM = 'pypi'
  1568. def __init__(self, fn=None, url=None):
  1569. if fn is None:
  1570. fn = os.path.join(os.path.expanduser('~'), '.pypirc')
  1571. self.filename = fn
  1572. self.url = url
  1573. def read(self):
  1574. result = {}
  1575. if os.path.exists(self.filename):
  1576. repository = self.url or self.DEFAULT_REPOSITORY
  1577. config = configparser.RawConfigParser()
  1578. config.read(self.filename)
  1579. sections = config.sections()
  1580. if 'distutils' in sections:
  1581. # let's get the list of servers
  1582. index_servers = config.get('distutils', 'index-servers')
  1583. _servers = [
  1584. server.strip() for server in index_servers.split('\n')
  1585. if server.strip() != ''
  1586. ]
  1587. if _servers == []:
  1588. # nothing set, let's try to get the default pypi
  1589. if 'pypi' in sections:
  1590. _servers = ['pypi']
  1591. else:
  1592. for server in _servers:
  1593. result = {'server': server}
  1594. result['username'] = config.get(server, 'username')
  1595. # optional params
  1596. for key, default in (('repository',
  1597. self.DEFAULT_REPOSITORY),
  1598. ('realm', self.DEFAULT_REALM),
  1599. ('password', None)):
  1600. if config.has_option(server, key):
  1601. result[key] = config.get(server, key)
  1602. else:
  1603. result[key] = default
  1604. # work around people having "repository" for the "pypi"
  1605. # section of their config set to the HTTP (rather than
  1606. # HTTPS) URL
  1607. if (server == 'pypi' and repository
  1608. in (self.DEFAULT_REPOSITORY, 'pypi')):
  1609. result['repository'] = self.DEFAULT_REPOSITORY
  1610. elif (result['server'] != repository
  1611. and result['repository'] != repository):
  1612. result = {}
  1613. elif 'server-login' in sections:
  1614. # old format
  1615. server = 'server-login'
  1616. if config.has_option(server, 'repository'):
  1617. repository = config.get(server, 'repository')
  1618. else:
  1619. repository = self.DEFAULT_REPOSITORY
  1620. result = {
  1621. 'username': config.get(server, 'username'),
  1622. 'password': config.get(server, 'password'),
  1623. 'repository': repository,
  1624. 'server': server,
  1625. 'realm': self.DEFAULT_REALM
  1626. }
  1627. return result
  1628. def update(self, username, password):
  1629. # import pdb; pdb.set_trace()
  1630. config = configparser.RawConfigParser()
  1631. fn = self.filename
  1632. config.read(fn)
  1633. if not config.has_section('pypi'):
  1634. config.add_section('pypi')
  1635. config.set('pypi', 'username', username)
  1636. config.set('pypi', 'password', password)
  1637. with open(fn, 'w') as f:
  1638. config.write(f)
  1639. def _load_pypirc(index):
  1640. """
  1641. Read the PyPI access configuration as supported by distutils.
  1642. """
  1643. return PyPIRCFile(url=index.url).read()
  1644. def _store_pypirc(index):
  1645. PyPIRCFile().update(index.username, index.password)
  1646. #
  1647. # get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor
  1648. # tweaks
  1649. #
  1650. def get_host_platform():
  1651. """Return a string that identifies the current platform. This is used mainly to
  1652. distinguish platform-specific build directories and platform-specific built
  1653. distributions. Typically includes the OS name and version and the
  1654. architecture (as supplied by 'os.uname()'), although the exact information
  1655. included depends on the OS; eg. on Linux, the kernel version isn't
  1656. particularly important.
  1657. Examples of returned values:
  1658. linux-i586
  1659. linux-alpha (?)
  1660. solaris-2.6-sun4u
  1661. Windows will return one of:
  1662. win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  1663. win32 (all others - specifically, sys.platform is returned)
  1664. For other non-POSIX platforms, currently just returns 'sys.platform'.
  1665. """
  1666. if os.name == 'nt':
  1667. if 'amd64' in sys.version.lower():
  1668. return 'win-amd64'
  1669. if '(arm)' in sys.version.lower():
  1670. return 'win-arm32'
  1671. if '(arm64)' in sys.version.lower():
  1672. return 'win-arm64'
  1673. return sys.platform
  1674. # Set for cross builds explicitly
  1675. if "_PYTHON_HOST_PLATFORM" in os.environ:
  1676. return os.environ["_PYTHON_HOST_PLATFORM"]
  1677. if os.name != 'posix' or not hasattr(os, 'uname'):
  1678. # XXX what about the architecture? NT is Intel or Alpha,
  1679. # Mac OS is M68k or PPC, etc.
  1680. return sys.platform
  1681. # Try to distinguish various flavours of Unix
  1682. (osname, host, release, version, machine) = os.uname()
  1683. # Convert the OS name to lowercase, remove '/' characters, and translate
  1684. # spaces (for "Power Macintosh")
  1685. osname = osname.lower().replace('/', '')
  1686. machine = machine.replace(' ', '_').replace('/', '-')
  1687. if osname[:5] == 'linux':
  1688. # At least on Linux/Intel, 'machine' is the processor --
  1689. # i386, etc.
  1690. # XXX what about Alpha, SPARC, etc?
  1691. return "%s-%s" % (osname, machine)
  1692. elif osname[:5] == 'sunos':
  1693. if release[0] >= '5': # SunOS 5 == Solaris 2
  1694. osname = 'solaris'
  1695. release = '%d.%s' % (int(release[0]) - 3, release[2:])
  1696. # We can't use 'platform.architecture()[0]' because a
  1697. # bootstrap problem. We use a dict to get an error
  1698. # if some suspicious happens.
  1699. bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}
  1700. machine += '.%s' % bitness[sys.maxsize]
  1701. # fall through to standard osname-release-machine representation
  1702. elif osname[:3] == 'aix':
  1703. from _aix_support import aix_platform
  1704. return aix_platform()
  1705. elif osname[:6] == 'cygwin':
  1706. osname = 'cygwin'
  1707. rel_re = re.compile(r'[\d.]+', re.ASCII)
  1708. m = rel_re.match(release)
  1709. if m:
  1710. release = m.group()
  1711. elif osname[:6] == 'darwin':
  1712. import _osx_support
  1713. try:
  1714. from distutils import sysconfig
  1715. except ImportError:
  1716. import sysconfig
  1717. osname, release, machine = _osx_support.get_platform_osx(
  1718. sysconfig.get_config_vars(), osname, release, machine)
  1719. return '%s-%s-%s' % (osname, release, machine)
  1720. _TARGET_TO_PLAT = {
  1721. 'x86': 'win32',
  1722. 'x64': 'win-amd64',
  1723. 'arm': 'win-arm32',
  1724. }
  1725. def get_platform():
  1726. if os.name != 'nt':
  1727. return get_host_platform()
  1728. cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')
  1729. if cross_compilation_target not in _TARGET_TO_PLAT:
  1730. return get_host_platform()
  1731. return _TARGET_TO_PLAT[cross_compilation_target]