compat.py 40 KB

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