PageRenderTime 635ms CodeModel.GetById 32ms RepoModel.GetById 4ms app.codeStats 0ms

/pip/_vendor/distlib/compat.py

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