PageRenderTime 50ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/venv/lib/python2.7/site-packages/pip/_vendor/distlib/compat.py

https://gitlab.com/ismailam/openexport
Python | 1102 lines | 1084 code | 8 blank | 10 comment | 14 complexity | 5a808decf0b0bd3a8138d9ee00a54e94 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2013-2014 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 absolute_import
  8. import os
  9. import re
  10. import sys
  11. if sys.version_info[0] < 3:
  12. from StringIO import StringIO
  13. string_types = basestring,
  14. text_type = unicode
  15. from types import FileType as file_type
  16. import __builtin__ as builtins
  17. import ConfigParser as configparser
  18. from ._backport import shutil
  19. from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
  20. from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
  21. pathname2url, ContentTooShortError, splittype)
  22. def quote(s):
  23. if isinstance(s, unicode):
  24. s = s.encode('utf-8')
  25. return _quote(s)
  26. import urllib2
  27. from urllib2 import (Request, urlopen, URLError, HTTPError,
  28. HTTPBasicAuthHandler, HTTPPasswordMgr,
  29. HTTPSHandler, HTTPHandler, HTTPRedirectHandler,
  30. build_opener)
  31. import httplib
  32. import xmlrpclib
  33. import Queue as queue
  34. from HTMLParser import HTMLParser
  35. import htmlentitydefs
  36. raw_input = raw_input
  37. from itertools import ifilter as filter
  38. from itertools import ifilterfalse as filterfalse
  39. _userprog = None
  40. def splituser(host):
  41. """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  42. global _userprog
  43. if _userprog is None:
  44. import re
  45. _userprog = re.compile('^(.*)@(.*)$')
  46. match = _userprog.match(host)
  47. if match: return match.group(1, 2)
  48. return None, host
  49. else:
  50. from io import StringIO
  51. string_types = str,
  52. text_type = str
  53. from io import TextIOWrapper as file_type
  54. import builtins
  55. import configparser
  56. import shutil
  57. from urllib.parse import (urlparse, urlunparse, urljoin, splituser, quote,
  58. unquote, urlsplit, urlunsplit, splittype)
  59. from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
  60. pathname2url,
  61. HTTPBasicAuthHandler, HTTPPasswordMgr,
  62. HTTPSHandler, HTTPHandler, HTTPRedirectHandler,
  63. build_opener)
  64. from urllib.error import HTTPError, URLError, ContentTooShortError
  65. import http.client as httplib
  66. import urllib.request as urllib2
  67. import xmlrpc.client as xmlrpclib
  68. import queue
  69. from html.parser import HTMLParser
  70. import html.entities as htmlentitydefs
  71. raw_input = input
  72. from itertools import filterfalse
  73. filter = filter
  74. try:
  75. from ssl import match_hostname, CertificateError
  76. except ImportError:
  77. class CertificateError(ValueError):
  78. pass
  79. def _dnsname_match(dn, hostname, max_wildcards=1):
  80. """Matching according to RFC 6125, section 6.4.3
  81. http://tools.ietf.org/html/rfc6125#section-6.4.3
  82. """
  83. pats = []
  84. if not dn:
  85. return False
  86. parts = dn.split('.')
  87. leftmost, remainder = parts[0], parts[1:]
  88. wildcards = leftmost.count('*')
  89. if wildcards > max_wildcards:
  90. # Issue #17980: avoid denials of service by refusing more
  91. # than one wildcard per fragment. A survery of established
  92. # policy among SSL implementations showed it to be a
  93. # reasonable choice.
  94. raise CertificateError(
  95. "too many wildcards in certificate DNS name: " + repr(dn))
  96. # speed up common case w/o wildcards
  97. if not wildcards:
  98. return dn.lower() == hostname.lower()
  99. # RFC 6125, section 6.4.3, subitem 1.
  100. # The client SHOULD NOT attempt to match a presented identifier in which
  101. # the wildcard character comprises a label other than the left-most label.
  102. if leftmost == '*':
  103. # When '*' is a fragment by itself, it matches a non-empty dotless
  104. # fragment.
  105. pats.append('[^.]+')
  106. elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
  107. # RFC 6125, section 6.4.3, subitem 3.
  108. # The client SHOULD NOT attempt to match a presented identifier
  109. # where the wildcard character is embedded within an A-label or
  110. # U-label of an internationalized domain name.
  111. pats.append(re.escape(leftmost))
  112. else:
  113. # Otherwise, '*' matches any dotless string, e.g. www*
  114. pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
  115. # add the remaining fragments, ignore any wildcards
  116. for frag in remainder:
  117. pats.append(re.escape(frag))
  118. pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
  119. return pat.match(hostname)
  120. def match_hostname(cert, hostname):
  121. """Verify that *cert* (in decoded format as returned by
  122. SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
  123. rules are followed, but IP addresses are not accepted for *hostname*.
  124. CertificateError is raised on failure. On success, the function
  125. returns nothing.
  126. """
  127. if not cert:
  128. raise ValueError("empty or no certificate, match_hostname needs a "
  129. "SSL socket or SSL context with either "
  130. "CERT_OPTIONAL or CERT_REQUIRED")
  131. dnsnames = []
  132. san = cert.get('subjectAltName', ())
  133. for key, value in san:
  134. if key == 'DNS':
  135. if _dnsname_match(value, hostname):
  136. return
  137. dnsnames.append(value)
  138. if not dnsnames:
  139. # The subject is only checked when there is no dNSName entry
  140. # in subjectAltName
  141. for sub in cert.get('subject', ()):
  142. for key, value in sub:
  143. # XXX according to RFC 2818, the most specific Common Name
  144. # must be used.
  145. if key == 'commonName':
  146. if _dnsname_match(value, hostname):
  147. return
  148. dnsnames.append(value)
  149. if len(dnsnames) > 1:
  150. raise CertificateError("hostname %r "
  151. "doesn't match either of %s"
  152. % (hostname, ', '.join(map(repr, dnsnames))))
  153. elif len(dnsnames) == 1:
  154. raise CertificateError("hostname %r "
  155. "doesn't match %r"
  156. % (hostname, dnsnames[0]))
  157. else:
  158. raise CertificateError("no appropriate commonName or "
  159. "subjectAltName fields were found")
  160. try:
  161. from types import SimpleNamespace as Container
  162. except ImportError:
  163. class Container(object):
  164. """
  165. A generic container for when multiple values need to be returned
  166. """
  167. def __init__(self, **kwargs):
  168. self.__dict__.update(kwargs)
  169. try:
  170. from shutil import which
  171. except ImportError:
  172. # Implementation from Python 3.3
  173. def which(cmd, mode=os.F_OK | os.X_OK, path=None):
  174. """Given a command, mode, and a PATH string, return the path which
  175. conforms to the given mode on the PATH, or None if there is no such
  176. file.
  177. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  178. of os.environ.get("PATH"), or can be overridden with a custom search
  179. path.
  180. """
  181. # Check that a given file can be accessed with the correct mode.
  182. # Additionally check that `file` is not a directory, as on Windows
  183. # directories pass the os.access check.
  184. def _access_check(fn, mode):
  185. return (os.path.exists(fn) and os.access(fn, mode)
  186. and not os.path.isdir(fn))
  187. # If we're given a path with a directory part, look it up directly rather
  188. # than referring to PATH directories. This includes checking relative to the
  189. # current directory, e.g. ./script
  190. if os.path.dirname(cmd):
  191. if _access_check(cmd, mode):
  192. return cmd
  193. return None
  194. if path is None:
  195. path = os.environ.get("PATH", os.defpath)
  196. if not path:
  197. return None
  198. path = path.split(os.pathsep)
  199. if sys.platform == "win32":
  200. # The current directory takes precedence on Windows.
  201. if not os.curdir in path:
  202. path.insert(0, os.curdir)
  203. # PATHEXT is necessary to check on Windows.
  204. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  205. # See if the given file matches any of the expected path extensions.
  206. # This will allow us to short circuit when given "python.exe".
  207. # If it does match, only test that one, otherwise we have to try
  208. # others.
  209. if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
  210. files = [cmd]
  211. else:
  212. files = [cmd + ext for ext in pathext]
  213. else:
  214. # On other platforms you don't have things like PATHEXT to tell you
  215. # what file suffixes are executable, so just pass on cmd as-is.
  216. files = [cmd]
  217. seen = set()
  218. for dir in path:
  219. normdir = os.path.normcase(dir)
  220. if not normdir in seen:
  221. seen.add(normdir)
  222. for thefile in files:
  223. name = os.path.join(dir, thefile)
  224. if _access_check(name, mode):
  225. return name
  226. return None
  227. # ZipFile is a context manager in 2.7, but not in 2.6
  228. from zipfile import ZipFile as BaseZipFile
  229. if hasattr(BaseZipFile, '__enter__'):
  230. ZipFile = BaseZipFile
  231. else:
  232. from zipfile import ZipExtFile as BaseZipExtFile
  233. class ZipExtFile(BaseZipExtFile):
  234. def __init__(self, base):
  235. self.__dict__.update(base.__dict__)
  236. def __enter__(self):
  237. return self
  238. def __exit__(self, *exc_info):
  239. self.close()
  240. # return None, so if an exception occurred, it will propagate
  241. class ZipFile(BaseZipFile):
  242. def __enter__(self):
  243. return self
  244. def __exit__(self, *exc_info):
  245. self.close()
  246. # return None, so if an exception occurred, it will propagate
  247. def open(self, *args, **kwargs):
  248. base = BaseZipFile.open(self, *args, **kwargs)
  249. return ZipExtFile(base)
  250. try:
  251. from platform import python_implementation
  252. except ImportError: # pragma: no cover
  253. def python_implementation():
  254. """Return a string identifying the Python implementation."""
  255. if 'PyPy' in sys.version:
  256. return 'PyPy'
  257. if os.name == 'java':
  258. return 'Jython'
  259. if sys.version.startswith('IronPython'):
  260. return 'IronPython'
  261. return 'CPython'
  262. try:
  263. import sysconfig
  264. except ImportError: # pragma: no cover
  265. from ._backport import sysconfig
  266. try:
  267. callable = callable
  268. except NameError: # pragma: no cover
  269. from collections import Callable
  270. def callable(obj):
  271. return isinstance(obj, Callable)
  272. try:
  273. fsencode = os.fsencode
  274. fsdecode = os.fsdecode
  275. except AttributeError: # pragma: no cover
  276. _fsencoding = sys.getfilesystemencoding()
  277. if _fsencoding == 'mbcs':
  278. _fserrors = 'strict'
  279. else:
  280. _fserrors = 'surrogateescape'
  281. def fsencode(filename):
  282. if isinstance(filename, bytes):
  283. return filename
  284. elif isinstance(filename, text_type):
  285. return filename.encode(_fsencoding, _fserrors)
  286. else:
  287. raise TypeError("expect bytes or str, not %s" %
  288. type(filename).__name__)
  289. def fsdecode(filename):
  290. if isinstance(filename, text_type):
  291. return filename
  292. elif isinstance(filename, bytes):
  293. return filename.decode(_fsencoding, _fserrors)
  294. else:
  295. raise TypeError("expect bytes or str, not %s" %
  296. type(filename).__name__)
  297. try:
  298. from tokenize import detect_encoding
  299. except ImportError: # pragma: no cover
  300. from codecs import BOM_UTF8, lookup
  301. import re
  302. cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
  303. def _get_normal_name(orig_enc):
  304. """Imitates get_normal_name in tokenizer.c."""
  305. # Only care about the first 12 characters.
  306. enc = orig_enc[:12].lower().replace("_", "-")
  307. if enc == "utf-8" or enc.startswith("utf-8-"):
  308. return "utf-8"
  309. if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
  310. enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
  311. return "iso-8859-1"
  312. return orig_enc
  313. def detect_encoding(readline):
  314. """
  315. The detect_encoding() function is used to detect the encoding that should
  316. be used to decode a Python source file. It requires one argment, readline,
  317. in the same way as the tokenize() generator.
  318. It will call readline a maximum of twice, and return the encoding used
  319. (as a string) and a list of any lines (left as bytes) it has read in.
  320. It detects the encoding from the presence of a utf-8 bom or an encoding
  321. cookie as specified in pep-0263. If both a bom and a cookie are present,
  322. but disagree, a SyntaxError will be raised. If the encoding cookie is an
  323. invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
  324. 'utf-8-sig' is returned.
  325. If no encoding is specified, then the default of 'utf-8' will be returned.
  326. """
  327. try:
  328. filename = readline.__self__.name
  329. except AttributeError:
  330. filename = None
  331. bom_found = False
  332. encoding = None
  333. default = 'utf-8'
  334. def read_or_stop():
  335. try:
  336. return readline()
  337. except StopIteration:
  338. return b''
  339. def find_cookie(line):
  340. try:
  341. # Decode as UTF-8. Either the line is an encoding declaration,
  342. # in which case it should be pure ASCII, or it must be UTF-8
  343. # per default encoding.
  344. line_string = line.decode('utf-8')
  345. except UnicodeDecodeError:
  346. msg = "invalid or missing encoding declaration"
  347. if filename is not None:
  348. msg = '{} for {!r}'.format(msg, filename)
  349. raise SyntaxError(msg)
  350. matches = cookie_re.findall(line_string)
  351. if not matches:
  352. return None
  353. encoding = _get_normal_name(matches[0])
  354. try:
  355. codec = lookup(encoding)
  356. except LookupError:
  357. # This behaviour mimics the Python interpreter
  358. if filename is None:
  359. msg = "unknown encoding: " + encoding
  360. else:
  361. msg = "unknown encoding for {!r}: {}".format(filename,
  362. encoding)
  363. raise SyntaxError(msg)
  364. if bom_found:
  365. if codec.name != 'utf-8':
  366. # This behaviour mimics the Python interpreter
  367. if filename is None:
  368. msg = 'encoding problem: utf-8'
  369. else:
  370. msg = 'encoding problem for {!r}: utf-8'.format(filename)
  371. raise SyntaxError(msg)
  372. encoding += '-sig'
  373. return encoding
  374. first = read_or_stop()
  375. if first.startswith(BOM_UTF8):
  376. bom_found = True
  377. first = first[3:]
  378. default = 'utf-8-sig'
  379. if not first:
  380. return default, []
  381. encoding = find_cookie(first)
  382. if encoding:
  383. return encoding, [first]
  384. second = read_or_stop()
  385. if not second:
  386. return default, [first]
  387. encoding = find_cookie(second)
  388. if encoding:
  389. return encoding, [first, second]
  390. return default, [first, second]
  391. # For converting & <-> &amp; etc.
  392. try:
  393. from html import escape
  394. except ImportError:
  395. from cgi import escape
  396. if sys.version_info[:2] < (3, 4):
  397. unescape = HTMLParser().unescape
  398. else:
  399. from html import unescape
  400. try:
  401. from collections import ChainMap
  402. except ImportError: # pragma: no cover
  403. from collections import MutableMapping
  404. try:
  405. from reprlib import recursive_repr as _recursive_repr
  406. except ImportError:
  407. def _recursive_repr(fillvalue='...'):
  408. '''
  409. Decorator to make a repr function return fillvalue for a recursive
  410. call
  411. '''
  412. def decorating_function(user_function):
  413. repr_running = set()
  414. def wrapper(self):
  415. key = id(self), get_ident()
  416. if key in repr_running:
  417. return fillvalue
  418. repr_running.add(key)
  419. try:
  420. result = user_function(self)
  421. finally:
  422. repr_running.discard(key)
  423. return result
  424. # Can't use functools.wraps() here because of bootstrap issues
  425. wrapper.__module__ = getattr(user_function, '__module__')
  426. wrapper.__doc__ = getattr(user_function, '__doc__')
  427. wrapper.__name__ = getattr(user_function, '__name__')
  428. wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
  429. return wrapper
  430. return decorating_function
  431. class ChainMap(MutableMapping):
  432. ''' A ChainMap groups multiple dicts (or other mappings) together
  433. to create a single, updateable view.
  434. The underlying mappings are stored in a list. That list is public and can
  435. accessed or updated using the *maps* attribute. There is no other state.
  436. Lookups search the underlying mappings successively until a key is found.
  437. In contrast, writes, updates, and deletions only operate on the first
  438. mapping.
  439. '''
  440. def __init__(self, *maps):
  441. '''Initialize a ChainMap by setting *maps* to the given mappings.
  442. If no mappings are provided, a single empty dictionary is used.
  443. '''
  444. self.maps = list(maps) or [{}] # always at least one map
  445. def __missing__(self, key):
  446. raise KeyError(key)
  447. def __getitem__(self, key):
  448. for mapping in self.maps:
  449. try:
  450. return mapping[key] # can't use 'key in mapping' with defaultdict
  451. except KeyError:
  452. pass
  453. return self.__missing__(key) # support subclasses that define __missing__
  454. def get(self, key, default=None):
  455. return self[key] if key in self else default
  456. def __len__(self):
  457. return len(set().union(*self.maps)) # reuses stored hash values if possible
  458. def __iter__(self):
  459. return iter(set().union(*self.maps))
  460. def __contains__(self, key):
  461. return any(key in m for m in self.maps)
  462. def __bool__(self):
  463. return any(self.maps)
  464. @_recursive_repr()
  465. def __repr__(self):
  466. return '{0.__class__.__name__}({1})'.format(
  467. self, ', '.join(map(repr, self.maps)))
  468. @classmethod
  469. def fromkeys(cls, iterable, *args):
  470. 'Create a ChainMap with a single dict created from the iterable.'
  471. return cls(dict.fromkeys(iterable, *args))
  472. def copy(self):
  473. 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
  474. return self.__class__(self.maps[0].copy(), *self.maps[1:])
  475. __copy__ = copy
  476. def new_child(self): # like Django's Context.push()
  477. 'New ChainMap with a new dict followed by all previous maps.'
  478. return self.__class__({}, *self.maps)
  479. @property
  480. def parents(self): # like Django's Context.pop()
  481. 'New ChainMap from maps[1:].'
  482. return self.__class__(*self.maps[1:])
  483. def __setitem__(self, key, value):
  484. self.maps[0][key] = value
  485. def __delitem__(self, key):
  486. try:
  487. del self.maps[0][key]
  488. except KeyError:
  489. raise KeyError('Key not found in the first mapping: {!r}'.format(key))
  490. def popitem(self):
  491. 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
  492. try:
  493. return self.maps[0].popitem()
  494. except KeyError:
  495. raise KeyError('No keys found in the first mapping.')
  496. def pop(self, key, *args):
  497. 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
  498. try:
  499. return self.maps[0].pop(key, *args)
  500. except KeyError:
  501. raise KeyError('Key not found in the first mapping: {!r}'.format(key))
  502. def clear(self):
  503. 'Clear maps[0], leaving maps[1:] intact.'
  504. self.maps[0].clear()
  505. try:
  506. from imp import cache_from_source
  507. except ImportError: # pragma: no cover
  508. def cache_from_source(path, debug_override=None):
  509. assert path.endswith('.py')
  510. if debug_override is None:
  511. debug_override = __debug__
  512. if debug_override:
  513. suffix = 'c'
  514. else:
  515. suffix = 'o'
  516. return path + suffix
  517. try:
  518. from collections import OrderedDict
  519. except ImportError: # pragma: no cover
  520. ## {{{ http://code.activestate.com/recipes/576693/ (r9)
  521. # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
  522. # Passes Python2.7's test suite and incorporates all the latest updates.
  523. try:
  524. from thread import get_ident as _get_ident
  525. except ImportError:
  526. from dummy_thread import get_ident as _get_ident
  527. try:
  528. from _abcoll import KeysView, ValuesView, ItemsView
  529. except ImportError:
  530. pass
  531. class OrderedDict(dict):
  532. 'Dictionary that remembers insertion order'
  533. # An inherited dict maps keys to values.
  534. # The inherited dict provides __getitem__, __len__, __contains__, and get.
  535. # The remaining methods are order-aware.
  536. # Big-O running times for all methods are the same as for regular dictionaries.
  537. # The internal self.__map dictionary maps keys to links in a doubly linked list.
  538. # The circular doubly linked list starts and ends with a sentinel element.
  539. # The sentinel element never gets deleted (this simplifies the algorithm).
  540. # Each link is stored as a list of length three: [PREV, NEXT, KEY].
  541. def __init__(self, *args, **kwds):
  542. '''Initialize an ordered dictionary. Signature is the same as for
  543. regular dictionaries, but keyword arguments are not recommended
  544. because their insertion order is arbitrary.
  545. '''
  546. if len(args) > 1:
  547. raise TypeError('expected at most 1 arguments, got %d' % len(args))
  548. try:
  549. self.__root
  550. except AttributeError:
  551. self.__root = root = [] # sentinel node
  552. root[:] = [root, root, None]
  553. self.__map = {}
  554. self.__update(*args, **kwds)
  555. def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
  556. 'od.__setitem__(i, y) <==> od[i]=y'
  557. # Setting a new item creates a new link which goes at the end of the linked
  558. # list, and the inherited dictionary is updated with the new key/value pair.
  559. if key not in self:
  560. root = self.__root
  561. last = root[0]
  562. last[1] = root[0] = self.__map[key] = [last, root, key]
  563. dict_setitem(self, key, value)
  564. def __delitem__(self, key, dict_delitem=dict.__delitem__):
  565. 'od.__delitem__(y) <==> del od[y]'
  566. # Deleting an existing item uses self.__map to find the link which is
  567. # then removed by updating the links in the predecessor and successor nodes.
  568. dict_delitem(self, key)
  569. link_prev, link_next, key = self.__map.pop(key)
  570. link_prev[1] = link_next
  571. link_next[0] = link_prev
  572. def __iter__(self):
  573. 'od.__iter__() <==> iter(od)'
  574. root = self.__root
  575. curr = root[1]
  576. while curr is not root:
  577. yield curr[2]
  578. curr = curr[1]
  579. def __reversed__(self):
  580. 'od.__reversed__() <==> reversed(od)'
  581. root = self.__root
  582. curr = root[0]
  583. while curr is not root:
  584. yield curr[2]
  585. curr = curr[0]
  586. def clear(self):
  587. 'od.clear() -> None. Remove all items from od.'
  588. try:
  589. for node in self.__map.itervalues():
  590. del node[:]
  591. root = self.__root
  592. root[:] = [root, root, None]
  593. self.__map.clear()
  594. except AttributeError:
  595. pass
  596. dict.clear(self)
  597. def popitem(self, last=True):
  598. '''od.popitem() -> (k, v), return and remove a (key, value) pair.
  599. Pairs are returned in LIFO order if last is true or FIFO order if false.
  600. '''
  601. if not self:
  602. raise KeyError('dictionary is empty')
  603. root = self.__root
  604. if last:
  605. link = root[0]
  606. link_prev = link[0]
  607. link_prev[1] = root
  608. root[0] = link_prev
  609. else:
  610. link = root[1]
  611. link_next = link[1]
  612. root[1] = link_next
  613. link_next[0] = root
  614. key = link[2]
  615. del self.__map[key]
  616. value = dict.pop(self, key)
  617. return key, value
  618. # -- the following methods do not depend on the internal structure --
  619. def keys(self):
  620. 'od.keys() -> list of keys in od'
  621. return list(self)
  622. def values(self):
  623. 'od.values() -> list of values in od'
  624. return [self[key] for key in self]
  625. def items(self):
  626. 'od.items() -> list of (key, value) pairs in od'
  627. return [(key, self[key]) for key in self]
  628. def iterkeys(self):
  629. 'od.iterkeys() -> an iterator over the keys in od'
  630. return iter(self)
  631. def itervalues(self):
  632. 'od.itervalues -> an iterator over the values in od'
  633. for k in self:
  634. yield self[k]
  635. def iteritems(self):
  636. 'od.iteritems -> an iterator over the (key, value) items in od'
  637. for k in self:
  638. yield (k, self[k])
  639. def update(*args, **kwds):
  640. '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
  641. If E is a dict instance, does: for k in E: od[k] = E[k]
  642. If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
  643. Or if E is an iterable of items, does: for k, v in E: od[k] = v
  644. In either case, this is followed by: for k, v in F.items(): od[k] = v
  645. '''
  646. if len(args) > 2:
  647. raise TypeError('update() takes at most 2 positional '
  648. 'arguments (%d given)' % (len(args),))
  649. elif not args:
  650. raise TypeError('update() takes at least 1 argument (0 given)')
  651. self = args[0]
  652. # Make progressively weaker assumptions about "other"
  653. other = ()
  654. if len(args) == 2:
  655. other = args[1]
  656. if isinstance(other, dict):
  657. for key in other:
  658. self[key] = other[key]
  659. elif hasattr(other, 'keys'):
  660. for key in other.keys():
  661. self[key] = other[key]
  662. else:
  663. for key, value in other:
  664. self[key] = value
  665. for key, value in kwds.items():
  666. self[key] = value
  667. __update = update # let subclasses override update without breaking __init__
  668. __marker = object()
  669. def pop(self, key, default=__marker):
  670. '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  671. If key is not found, d is returned if given, otherwise KeyError is raised.
  672. '''
  673. if key in self:
  674. result = self[key]
  675. del self[key]
  676. return result
  677. if default is self.__marker:
  678. raise KeyError(key)
  679. return default
  680. def setdefault(self, key, default=None):
  681. 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
  682. if key in self:
  683. return self[key]
  684. self[key] = default
  685. return default
  686. def __repr__(self, _repr_running=None):
  687. 'od.__repr__() <==> repr(od)'
  688. if not _repr_running: _repr_running = {}
  689. call_key = id(self), _get_ident()
  690. if call_key in _repr_running:
  691. return '...'
  692. _repr_running[call_key] = 1
  693. try:
  694. if not self:
  695. return '%s()' % (self.__class__.__name__,)
  696. return '%s(%r)' % (self.__class__.__name__, self.items())
  697. finally:
  698. del _repr_running[call_key]
  699. def __reduce__(self):
  700. 'Return state information for pickling'
  701. items = [[k, self[k]] for k in self]
  702. inst_dict = vars(self).copy()
  703. for k in vars(OrderedDict()):
  704. inst_dict.pop(k, None)
  705. if inst_dict:
  706. return (self.__class__, (items,), inst_dict)
  707. return self.__class__, (items,)
  708. def copy(self):
  709. 'od.copy() -> a shallow copy of od'
  710. return self.__class__(self)
  711. @classmethod
  712. def fromkeys(cls, iterable, value=None):
  713. '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
  714. and values equal to v (which defaults to None).
  715. '''
  716. d = cls()
  717. for key in iterable:
  718. d[key] = value
  719. return d
  720. def __eq__(self, other):
  721. '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
  722. while comparison to a regular mapping is order-insensitive.
  723. '''
  724. if isinstance(other, OrderedDict):
  725. return len(self)==len(other) and self.items() == other.items()
  726. return dict.__eq__(self, other)
  727. def __ne__(self, other):
  728. return not self == other
  729. # -- the following methods are only used in Python 2.7 --
  730. def viewkeys(self):
  731. "od.viewkeys() -> a set-like object providing a view on od's keys"
  732. return KeysView(self)
  733. def viewvalues(self):
  734. "od.viewvalues() -> an object providing a view on od's values"
  735. return ValuesView(self)
  736. def viewitems(self):
  737. "od.viewitems() -> a set-like object providing a view on od's items"
  738. return ItemsView(self)
  739. try:
  740. from logging.config import BaseConfigurator, valid_ident
  741. except ImportError: # pragma: no cover
  742. IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
  743. def valid_ident(s):
  744. m = IDENTIFIER.match(s)
  745. if not m:
  746. raise ValueError('Not a valid Python identifier: %r' % s)
  747. return True
  748. # The ConvertingXXX classes are wrappers around standard Python containers,
  749. # and they serve to convert any suitable values in the container. The
  750. # conversion converts base dicts, lists and tuples to their wrapped
  751. # equivalents, whereas strings which match a conversion format are converted
  752. # appropriately.
  753. #
  754. # Each wrapper should have a configurator attribute holding the actual
  755. # configurator to use for conversion.
  756. class ConvertingDict(dict):
  757. """A converting dictionary wrapper."""
  758. def __getitem__(self, key):
  759. value = dict.__getitem__(self, key)
  760. result = self.configurator.convert(value)
  761. #If the converted value is different, save for next time
  762. if value is not result:
  763. self[key] = result
  764. if type(result) in (ConvertingDict, ConvertingList,
  765. ConvertingTuple):
  766. result.parent = self
  767. result.key = key
  768. return result
  769. def get(self, key, default=None):
  770. value = dict.get(self, key, default)
  771. result = self.configurator.convert(value)
  772. #If the converted value is different, save for next time
  773. if value is not result:
  774. self[key] = result
  775. if type(result) in (ConvertingDict, ConvertingList,
  776. ConvertingTuple):
  777. result.parent = self
  778. result.key = key
  779. return result
  780. def pop(self, key, default=None):
  781. value = dict.pop(self, key, default)
  782. result = self.configurator.convert(value)
  783. if value is not result:
  784. if type(result) in (ConvertingDict, ConvertingList,
  785. ConvertingTuple):
  786. result.parent = self
  787. result.key = key
  788. return result
  789. class ConvertingList(list):
  790. """A converting list wrapper."""
  791. def __getitem__(self, key):
  792. value = list.__getitem__(self, key)
  793. result = self.configurator.convert(value)
  794. #If the converted value is different, save for next time
  795. if value is not result:
  796. self[key] = result
  797. if type(result) in (ConvertingDict, ConvertingList,
  798. ConvertingTuple):
  799. result.parent = self
  800. result.key = key
  801. return result
  802. def pop(self, idx=-1):
  803. value = list.pop(self, idx)
  804. result = self.configurator.convert(value)
  805. if value is not result:
  806. if type(result) in (ConvertingDict, ConvertingList,
  807. ConvertingTuple):
  808. result.parent = self
  809. return result
  810. class ConvertingTuple(tuple):
  811. """A converting tuple wrapper."""
  812. def __getitem__(self, key):
  813. value = tuple.__getitem__(self, key)
  814. result = self.configurator.convert(value)
  815. if value is not result:
  816. if type(result) in (ConvertingDict, ConvertingList,
  817. ConvertingTuple):
  818. result.parent = self
  819. result.key = key
  820. return result
  821. class BaseConfigurator(object):
  822. """
  823. The configurator base class which defines some useful defaults.
  824. """
  825. CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
  826. WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
  827. DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
  828. INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
  829. DIGIT_PATTERN = re.compile(r'^\d+$')
  830. value_converters = {
  831. 'ext' : 'ext_convert',
  832. 'cfg' : 'cfg_convert',
  833. }
  834. # We might want to use a different one, e.g. importlib
  835. importer = staticmethod(__import__)
  836. def __init__(self, config):
  837. self.config = ConvertingDict(config)
  838. self.config.configurator = self
  839. def resolve(self, s):
  840. """
  841. Resolve strings to objects using standard import and attribute
  842. syntax.
  843. """
  844. name = s.split('.')
  845. used = name.pop(0)
  846. try:
  847. found = self.importer(used)
  848. for frag in name:
  849. used += '.' + frag
  850. try:
  851. found = getattr(found, frag)
  852. except AttributeError:
  853. self.importer(used)
  854. found = getattr(found, frag)
  855. return found
  856. except ImportError:
  857. e, tb = sys.exc_info()[1:]
  858. v = ValueError('Cannot resolve %r: %s' % (s, e))
  859. v.__cause__, v.__traceback__ = e, tb
  860. raise v
  861. def ext_convert(self, value):
  862. """Default converter for the ext:// protocol."""
  863. return self.resolve(value)
  864. def cfg_convert(self, value):
  865. """Default converter for the cfg:// protocol."""
  866. rest = value
  867. m = self.WORD_PATTERN.match(rest)
  868. if m is None:
  869. raise ValueError("Unable to convert %r" % value)
  870. else:
  871. rest = rest[m.end():]
  872. d = self.config[m.groups()[0]]
  873. #print d, rest
  874. while rest:
  875. m = self.DOT_PATTERN.match(rest)
  876. if m:
  877. d = d[m.groups()[0]]
  878. else:
  879. m = self.INDEX_PATTERN.match(rest)
  880. if m:
  881. idx = m.groups()[0]
  882. if not self.DIGIT_PATTERN.match(idx):
  883. d = d[idx]
  884. else:
  885. try:
  886. n = int(idx) # try as number first (most likely)
  887. d = d[n]
  888. except TypeError:
  889. d = d[idx]
  890. if m:
  891. rest = rest[m.end():]
  892. else:
  893. raise ValueError('Unable to convert '
  894. '%r at %r' % (value, rest))
  895. #rest should be empty
  896. return d
  897. def convert(self, value):
  898. """
  899. Convert values to an appropriate type. dicts, lists and tuples are
  900. replaced by their converting alternatives. Strings are checked to
  901. see if they have a conversion format and are converted if they do.
  902. """
  903. if not isinstance(value, ConvertingDict) and isinstance(value, dict):
  904. value = ConvertingDict(value)
  905. value.configurator = self
  906. elif not isinstance(value, ConvertingList) and isinstance(value, list):
  907. value = ConvertingList(value)
  908. value.configurator = self
  909. elif not isinstance(value, ConvertingTuple) and\
  910. isinstance(value, tuple):
  911. value = ConvertingTuple(value)
  912. value.configurator = self
  913. elif isinstance(value, string_types):
  914. m = self.CONVERT_PATTERN.match(value)
  915. if m:
  916. d = m.groupdict()
  917. prefix = d['prefix']
  918. converter = self.value_converters.get(prefix, None)
  919. if converter:
  920. suffix = d['suffix']
  921. converter = getattr(self, converter)
  922. value = converter(suffix)
  923. return value
  924. def configure_custom(self, config):
  925. """Configure an object with a user-supplied factory."""
  926. c = config.pop('()')
  927. if not callable(c):
  928. c = self.resolve(c)
  929. props = config.pop('.', None)
  930. # Check for valid identifiers
  931. kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
  932. result = c(**kwargs)
  933. if props:
  934. for name, value in props.items():
  935. setattr(result, name, value)
  936. return result
  937. def as_tuple(self, value):
  938. """Utility function which converts lists to tuples."""
  939. if isinstance(value, list):
  940. value = tuple(value)
  941. return value