PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/configobj.py

https://bitbucket.org/atze/youtube-autoload
Python | 2499 lines | 2387 code | 50 blank | 62 comment | 30 complexity | 6579cdb663d995cc709a375d1430ab55 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # configobj.py
  2. # A config file reader/writer that supports nested sections in config files.
  3. # Copyright (C) 2005-2008 Michael Foord, Nicola Larosa
  4. # E-mail: fuzzyman AT voidspace DOT org DOT uk
  5. # nico AT tekNico DOT net
  6. # ConfigObj 4
  7. # http://www.voidspace.org.uk/python/configobj.html
  8. # Released subject to the BSD License
  9. # Please see http://www.voidspace.org.uk/python/license.shtml
  10. # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
  11. # For information about bugfixes, updates and support, please join the
  12. # ConfigObj mailing list:
  13. # http://lists.sourceforge.net/lists/listinfo/configobj-develop
  14. # Comments, suggestions and bug reports welcome.
  15. from __future__ import generators
  16. import sys
  17. INTP_VER = sys.version_info[:2]
  18. if INTP_VER < (2, 2):
  19. raise RuntimeError("Python v.2.2 or later needed")
  20. import os, re
  21. compiler = None
  22. try:
  23. import compiler
  24. except ImportError:
  25. # for IronPython
  26. pass
  27. from types import StringTypes
  28. from warnings import warn
  29. try:
  30. from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
  31. except ImportError:
  32. # Python 2.2 does not have these
  33. # UTF-8
  34. BOM_UTF8 = '\xef\xbb\xbf'
  35. # UTF-16, little endian
  36. BOM_UTF16_LE = '\xff\xfe'
  37. # UTF-16, big endian
  38. BOM_UTF16_BE = '\xfe\xff'
  39. if sys.byteorder == 'little':
  40. # UTF-16, native endianness
  41. BOM_UTF16 = BOM_UTF16_LE
  42. else:
  43. # UTF-16, native endianness
  44. BOM_UTF16 = BOM_UTF16_BE
  45. # A dictionary mapping BOM to
  46. # the encoding to decode with, and what to set the
  47. # encoding attribute to.
  48. BOMS = {
  49. BOM_UTF8: ('utf_8', None),
  50. BOM_UTF16_BE: ('utf16_be', 'utf_16'),
  51. BOM_UTF16_LE: ('utf16_le', 'utf_16'),
  52. BOM_UTF16: ('utf_16', 'utf_16'),
  53. }
  54. # All legal variants of the BOM codecs.
  55. # TODO: the list of aliases is not meant to be exhaustive, is there a
  56. # better way ?
  57. BOM_LIST = {
  58. 'utf_16': 'utf_16',
  59. 'u16': 'utf_16',
  60. 'utf16': 'utf_16',
  61. 'utf-16': 'utf_16',
  62. 'utf16_be': 'utf16_be',
  63. 'utf_16_be': 'utf16_be',
  64. 'utf-16be': 'utf16_be',
  65. 'utf16_le': 'utf16_le',
  66. 'utf_16_le': 'utf16_le',
  67. 'utf-16le': 'utf16_le',
  68. 'utf_8': 'utf_8',
  69. 'u8': 'utf_8',
  70. 'utf': 'utf_8',
  71. 'utf8': 'utf_8',
  72. 'utf-8': 'utf_8',
  73. }
  74. # Map of encodings to the BOM to write.
  75. BOM_SET = {
  76. 'utf_8': BOM_UTF8,
  77. 'utf_16': BOM_UTF16,
  78. 'utf16_be': BOM_UTF16_BE,
  79. 'utf16_le': BOM_UTF16_LE,
  80. None: BOM_UTF8
  81. }
  82. def match_utf8(encoding):
  83. return BOM_LIST.get(encoding.lower()) == 'utf_8'
  84. # Quote strings used for writing values
  85. squot = "'%s'"
  86. dquot = '"%s"'
  87. noquot = "%s"
  88. wspace_plus = ' \r\t\n\v\t\'"'
  89. tsquot = '"""%s"""'
  90. tdquot = "'''%s'''"
  91. try:
  92. enumerate
  93. except NameError:
  94. def enumerate(obj):
  95. """enumerate for Python 2.2."""
  96. i = -1
  97. for item in obj:
  98. i += 1
  99. yield i, item
  100. try:
  101. True, False
  102. except NameError:
  103. True, False = 1, 0
  104. __version__ = '4.5.3'
  105. __revision__ = '$Id: configobj.py 156 2006-01-31 14:57:08Z fuzzyman $'
  106. __docformat__ = "restructuredtext en"
  107. __all__ = (
  108. '__version__',
  109. 'DEFAULT_INDENT_TYPE',
  110. 'DEFAULT_INTERPOLATION',
  111. 'ConfigObjError',
  112. 'NestingError',
  113. 'ParseError',
  114. 'DuplicateError',
  115. 'ConfigspecError',
  116. 'ConfigObj',
  117. 'SimpleVal',
  118. 'InterpolationError',
  119. 'InterpolationLoopError',
  120. 'MissingInterpolationOption',
  121. 'RepeatSectionError',
  122. 'ReloadError',
  123. 'UnreprError',
  124. 'UnknownType',
  125. '__docformat__',
  126. 'flatten_errors',
  127. )
  128. DEFAULT_INTERPOLATION = 'configparser'
  129. DEFAULT_INDENT_TYPE = ' '
  130. MAX_INTERPOL_DEPTH = 10
  131. OPTION_DEFAULTS = {
  132. 'interpolation': True,
  133. 'raise_errors': False,
  134. 'list_values': True,
  135. 'create_empty': False,
  136. 'file_error': False,
  137. 'configspec': None,
  138. 'stringify': True,
  139. # option may be set to one of ('', ' ', '\t')
  140. 'indent_type': None,
  141. 'encoding': None,
  142. 'default_encoding': None,
  143. 'unrepr': False,
  144. 'write_empty_values': False,
  145. }
  146. def getObj(s):
  147. s = "a=" + s
  148. if compiler is None:
  149. raise ImportError('compiler module not available')
  150. p = compiler.parse(s)
  151. return p.getChildren()[1].getChildren()[0].getChildren()[1]
  152. class UnknownType(Exception):
  153. pass
  154. class Builder(object):
  155. def build(self, o):
  156. m = getattr(self, 'build_' + o.__class__.__name__, None)
  157. if m is None:
  158. raise UnknownType(o.__class__.__name__)
  159. return m(o)
  160. def build_List(self, o):
  161. return map(self.build, o.getChildren())
  162. def build_Const(self, o):
  163. return o.value
  164. def build_Dict(self, o):
  165. d = {}
  166. i = iter(map(self.build, o.getChildren()))
  167. for el in i:
  168. d[el] = i.next()
  169. return d
  170. def build_Tuple(self, o):
  171. return tuple(self.build_List(o))
  172. def build_Name(self, o):
  173. if o.name == 'None':
  174. return None
  175. if o.name == 'True':
  176. return True
  177. if o.name == 'False':
  178. return False
  179. # An undefined Name
  180. raise UnknownType('Undefined Name')
  181. def build_Add(self, o):
  182. real, imag = map(self.build_Const, o.getChildren())
  183. try:
  184. real = float(real)
  185. except TypeError:
  186. raise UnknownType('Add')
  187. if not isinstance(imag, complex) or imag.real != 0.0:
  188. raise UnknownType('Add')
  189. return real+imag
  190. def build_Getattr(self, o):
  191. parent = self.build(o.expr)
  192. return getattr(parent, o.attrname)
  193. def build_UnarySub(self, o):
  194. return -self.build_Const(o.getChildren()[0])
  195. def build_UnaryAdd(self, o):
  196. return self.build_Const(o.getChildren()[0])
  197. _builder = Builder()
  198. def unrepr(s):
  199. if not s:
  200. return s
  201. return _builder.build(getObj(s))
  202. class ConfigObjError(SyntaxError):
  203. """
  204. This is the base class for all errors that ConfigObj raises.
  205. It is a subclass of SyntaxError.
  206. """
  207. def __init__(self, message='', line_number=None, line=''):
  208. self.line = line
  209. self.line_number = line_number
  210. self.message = message
  211. SyntaxError.__init__(self, message)
  212. class NestingError(ConfigObjError):
  213. """
  214. This error indicates a level of nesting that doesn't match.
  215. """
  216. class ParseError(ConfigObjError):
  217. """
  218. This error indicates that a line is badly written.
  219. It is neither a valid ``key = value`` line,
  220. nor a valid section marker line.
  221. """
  222. class ReloadError(IOError):
  223. """
  224. A 'reload' operation failed.
  225. This exception is a subclass of ``IOError``.
  226. """
  227. def __init__(self):
  228. IOError.__init__(self, 'reload failed, filename is not set.')
  229. class DuplicateError(ConfigObjError):
  230. """
  231. The keyword or section specified already exists.
  232. """
  233. class ConfigspecError(ConfigObjError):
  234. """
  235. An error occured whilst parsing a configspec.
  236. """
  237. class InterpolationError(ConfigObjError):
  238. """Base class for the two interpolation errors."""
  239. class InterpolationLoopError(InterpolationError):
  240. """Maximum interpolation depth exceeded in string interpolation."""
  241. def __init__(self, option):
  242. InterpolationError.__init__(
  243. self,
  244. 'interpolation loop detected in value "%s".' % option)
  245. class RepeatSectionError(ConfigObjError):
  246. """
  247. This error indicates additional sections in a section with a
  248. ``__many__`` (repeated) section.
  249. """
  250. class MissingInterpolationOption(InterpolationError):
  251. """A value specified for interpolation was missing."""
  252. def __init__(self, option):
  253. InterpolationError.__init__(
  254. self,
  255. 'missing option "%s" in interpolation.' % option)
  256. class UnreprError(ConfigObjError):
  257. """An error parsing in unrepr mode."""
  258. class InterpolationEngine(object):
  259. """
  260. A helper class to help perform string interpolation.
  261. This class is an abstract base class; its descendants perform
  262. the actual work.
  263. """
  264. # compiled regexp to use in self.interpolate()
  265. _KEYCRE = re.compile(r"%\(([^)]*)\)s")
  266. def __init__(self, section):
  267. # the Section instance that "owns" this engine
  268. self.section = section
  269. def interpolate(self, key, value):
  270. def recursive_interpolate(key, value, section, backtrail):
  271. """The function that does the actual work.
  272. ``value``: the string we're trying to interpolate.
  273. ``section``: the section in which that string was found
  274. ``backtrail``: a dict to keep track of where we've been,
  275. to detect and prevent infinite recursion loops
  276. This is similar to a depth-first-search algorithm.
  277. """
  278. # Have we been here already?
  279. if backtrail.has_key((key, section.name)):
  280. # Yes - infinite loop detected
  281. raise InterpolationLoopError(key)
  282. # Place a marker on our backtrail so we won't come back here again
  283. backtrail[(key, section.name)] = 1
  284. # Now start the actual work
  285. match = self._KEYCRE.search(value)
  286. while match:
  287. # The actual parsing of the match is implementation-dependent,
  288. # so delegate to our helper function
  289. k, v, s = self._parse_match(match)
  290. if k is None:
  291. # That's the signal that no further interpolation is needed
  292. replacement = v
  293. else:
  294. # Further interpolation may be needed to obtain final value
  295. replacement = recursive_interpolate(k, v, s, backtrail)
  296. # Replace the matched string with its final value
  297. start, end = match.span()
  298. value = ''.join((value[:start], replacement, value[end:]))
  299. new_search_start = start + len(replacement)
  300. # Pick up the next interpolation key, if any, for next time
  301. # through the while loop
  302. match = self._KEYCRE.search(value, new_search_start)
  303. # Now safe to come back here again; remove marker from backtrail
  304. del backtrail[(key, section.name)]
  305. return value
  306. # Back in interpolate(), all we have to do is kick off the recursive
  307. # function with appropriate starting values
  308. value = recursive_interpolate(key, value, self.section, {})
  309. return value
  310. def _fetch(self, key):
  311. """Helper function to fetch values from owning section.
  312. Returns a 2-tuple: the value, and the section where it was found.
  313. """
  314. # switch off interpolation before we try and fetch anything !
  315. save_interp = self.section.main.interpolation
  316. self.section.main.interpolation = False
  317. # Start at section that "owns" this InterpolationEngine
  318. current_section = self.section
  319. while True:
  320. # try the current section first
  321. val = current_section.get(key)
  322. if val is not None:
  323. break
  324. # try "DEFAULT" next
  325. val = current_section.get('DEFAULT', {}).get(key)
  326. if val is not None:
  327. break
  328. # move up to parent and try again
  329. # top-level's parent is itself
  330. if current_section.parent is current_section:
  331. # reached top level, time to give up
  332. break
  333. current_section = current_section.parent
  334. # restore interpolation to previous value before returning
  335. self.section.main.interpolation = save_interp
  336. if val is None:
  337. raise MissingInterpolationOption(key)
  338. return val, current_section
  339. def _parse_match(self, match):
  340. """Implementation-dependent helper function.
  341. Will be passed a match object corresponding to the interpolation
  342. key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
  343. key in the appropriate config file section (using the ``_fetch()``
  344. helper function) and return a 3-tuple: (key, value, section)
  345. ``key`` is the name of the key we're looking for
  346. ``value`` is the value found for that key
  347. ``section`` is a reference to the section where it was found
  348. ``key`` and ``section`` should be None if no further
  349. interpolation should be performed on the resulting value
  350. (e.g., if we interpolated "$$" and returned "$").
  351. """
  352. raise NotImplementedError()
  353. class ConfigParserInterpolation(InterpolationEngine):
  354. """Behaves like ConfigParser."""
  355. _KEYCRE = re.compile(r"%\(([^)]*)\)s")
  356. def _parse_match(self, match):
  357. key = match.group(1)
  358. value, section = self._fetch(key)
  359. return key, value, section
  360. class TemplateInterpolation(InterpolationEngine):
  361. """Behaves like string.Template."""
  362. _delimiter = '$'
  363. _KEYCRE = re.compile(r"""
  364. \$(?:
  365. (?P<escaped>\$) | # Two $ signs
  366. (?P<named>[_a-z][_a-z0-9]*) | # $name format
  367. {(?P<braced>[^}]*)} # ${name} format
  368. )
  369. """, re.IGNORECASE | re.VERBOSE)
  370. def _parse_match(self, match):
  371. # Valid name (in or out of braces): fetch value from section
  372. key = match.group('named') or match.group('braced')
  373. if key is not None:
  374. value, section = self._fetch(key)
  375. return key, value, section
  376. # Escaped delimiter (e.g., $$): return single delimiter
  377. if match.group('escaped') is not None:
  378. # Return None for key and section to indicate it's time to stop
  379. return None, self._delimiter, None
  380. # Anything else: ignore completely, just return it unchanged
  381. return None, match.group(), None
  382. interpolation_engines = {
  383. 'configparser': ConfigParserInterpolation,
  384. 'template': TemplateInterpolation,
  385. }
  386. class Section(dict):
  387. """
  388. A dictionary-like object that represents a section in a config file.
  389. It does string interpolation if the 'interpolation' attribute
  390. of the 'main' object is set to True.
  391. Interpolation is tried first from this object, then from the 'DEFAULT'
  392. section of this object, next from the parent and its 'DEFAULT' section,
  393. and so on until the main object is reached.
  394. A Section will behave like an ordered dictionary - following the
  395. order of the ``scalars`` and ``sections`` attributes.
  396. You can use this to change the order of members.
  397. Iteration follows the order: scalars, then sections.
  398. """
  399. def __init__(self, parent, depth, main, indict=None, name=None):
  400. """
  401. * parent is the section above
  402. * depth is the depth level of this section
  403. * main is the main ConfigObj
  404. * indict is a dictionary to initialise the section with
  405. """
  406. if indict is None:
  407. indict = {}
  408. dict.__init__(self)
  409. # used for nesting level *and* interpolation
  410. self.parent = parent
  411. # used for the interpolation attribute
  412. self.main = main
  413. # level of nesting depth of this Section
  414. self.depth = depth
  415. # purely for information
  416. self.name = name
  417. #
  418. self._initialise()
  419. # we do this explicitly so that __setitem__ is used properly
  420. # (rather than just passing to ``dict.__init__``)
  421. for entry, value in indict.iteritems():
  422. self[entry] = value
  423. def _initialise(self):
  424. # the sequence of scalar values in this Section
  425. self.scalars = []
  426. # the sequence of sections in this Section
  427. self.sections = []
  428. # for comments :-)
  429. self.comments = {}
  430. self.inline_comments = {}
  431. # for the configspec
  432. self.configspec = {}
  433. self._order = []
  434. self._configspec_comments = {}
  435. self._configspec_inline_comments = {}
  436. self._cs_section_comments = {}
  437. self._cs_section_inline_comments = {}
  438. # for defaults
  439. self.defaults = []
  440. self.default_values = {}
  441. def _interpolate(self, key, value):
  442. try:
  443. # do we already have an interpolation engine?
  444. engine = self._interpolation_engine
  445. except AttributeError:
  446. # not yet: first time running _interpolate(), so pick the engine
  447. name = self.main.interpolation
  448. if name == True: # note that "if name:" would be incorrect here
  449. # backwards-compatibility: interpolation=True means use default
  450. name = DEFAULT_INTERPOLATION
  451. name = name.lower() # so that "Template", "template", etc. all work
  452. class_ = interpolation_engines.get(name, None)
  453. if class_ is None:
  454. # invalid value for self.main.interpolation
  455. self.main.interpolation = False
  456. return value
  457. else:
  458. # save reference to engine so we don't have to do this again
  459. engine = self._interpolation_engine = class_(self)
  460. # let the engine do the actual work
  461. return engine.interpolate(key, value)
  462. def __getitem__(self, key):
  463. """Fetch the item and do string interpolation."""
  464. val = dict.__getitem__(self, key)
  465. if self.main.interpolation and isinstance(val, StringTypes):
  466. return self._interpolate(key, val)
  467. return val
  468. def __setitem__(self, key, value, unrepr=False):
  469. """
  470. Correctly set a value.
  471. Making dictionary values Section instances.
  472. (We have to special case 'Section' instances - which are also dicts)
  473. Keys must be strings.
  474. Values need only be strings (or lists of strings) if
  475. ``main.stringify`` is set.
  476. `unrepr`` must be set when setting a value to a dictionary, without
  477. creating a new sub-section.
  478. """
  479. if not isinstance(key, StringTypes):
  480. raise ValueError('The key "%s" is not a string.' % key)
  481. # add the comment
  482. if not self.comments.has_key(key):
  483. self.comments[key] = []
  484. self.inline_comments[key] = ''
  485. # remove the entry from defaults
  486. if key in self.defaults:
  487. self.defaults.remove(key)
  488. #
  489. if isinstance(value, Section):
  490. if not self.has_key(key):
  491. self.sections.append(key)
  492. dict.__setitem__(self, key, value)
  493. elif isinstance(value, dict) and not unrepr:
  494. # First create the new depth level,
  495. # then create the section
  496. if not self.has_key(key):
  497. self.sections.append(key)
  498. new_depth = self.depth + 1
  499. dict.__setitem__(
  500. self,
  501. key,
  502. Section(
  503. self,
  504. new_depth,
  505. self.main,
  506. indict=value,
  507. name=key))
  508. else:
  509. if not self.has_key(key):
  510. self.scalars.append(key)
  511. if not self.main.stringify:
  512. if isinstance(value, StringTypes):
  513. pass
  514. elif isinstance(value, (list, tuple)):
  515. for entry in value:
  516. if not isinstance(entry, StringTypes):
  517. raise TypeError('Value is not a string "%s".' % entry)
  518. else:
  519. raise TypeError('Value is not a string "%s".' % value)
  520. dict.__setitem__(self, key, value)
  521. def __delitem__(self, key):
  522. """Remove items from the sequence when deleting."""
  523. dict. __delitem__(self, key)
  524. if key in self.scalars:
  525. self.scalars.remove(key)
  526. else:
  527. self.sections.remove(key)
  528. del self.comments[key]
  529. del self.inline_comments[key]
  530. def get(self, key, default=None):
  531. """A version of ``get`` that doesn't bypass string interpolation."""
  532. try:
  533. return self[key]
  534. except KeyError:
  535. return default
  536. def update(self, indict):
  537. """
  538. A version of update that uses our ``__setitem__``.
  539. """
  540. for entry in indict:
  541. self[entry] = indict[entry]
  542. def pop(self, key, *args):
  543. """
  544. 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  545. If key is not found, d is returned if given, otherwise KeyError is raised'
  546. """
  547. val = dict.pop(self, key, *args)
  548. if key in self.scalars:
  549. del self.comments[key]
  550. del self.inline_comments[key]
  551. self.scalars.remove(key)
  552. elif key in self.sections:
  553. del self.comments[key]
  554. del self.inline_comments[key]
  555. self.sections.remove(key)
  556. if self.main.interpolation and isinstance(val, StringTypes):
  557. return self._interpolate(key, val)
  558. return val
  559. def popitem(self):
  560. """Pops the first (key,val)"""
  561. sequence = (self.scalars + self.sections)
  562. if not sequence:
  563. raise KeyError(": 'popitem(): dictionary is empty'")
  564. key = sequence[0]
  565. val = self[key]
  566. del self[key]
  567. return key, val
  568. def clear(self):
  569. """
  570. A version of clear that also affects scalars/sections
  571. Also clears comments and configspec.
  572. Leaves other attributes alone :
  573. depth/main/parent are not affected
  574. """
  575. dict.clear(self)
  576. self.scalars = []
  577. self.sections = []
  578. self.comments = {}
  579. self.inline_comments = {}
  580. self.configspec = {}
  581. def setdefault(self, key, default=None):
  582. """A version of setdefault that sets sequence if appropriate."""
  583. try:
  584. return self[key]
  585. except KeyError:
  586. self[key] = default
  587. return self[key]
  588. def items(self):
  589. """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
  590. return zip((self.scalars + self.sections), self.values())
  591. def keys(self):
  592. """D.keys() -> list of D's keys"""
  593. return (self.scalars + self.sections)
  594. def values(self):
  595. """D.values() -> list of D's values"""
  596. return [self[key] for key in (self.scalars + self.sections)]
  597. def iteritems(self):
  598. """D.iteritems() -> an iterator over the (key, value) items of D"""
  599. return iter(self.items())
  600. def iterkeys(self):
  601. """D.iterkeys() -> an iterator over the keys of D"""
  602. return iter((self.scalars + self.sections))
  603. __iter__ = iterkeys
  604. def itervalues(self):
  605. """D.itervalues() -> an iterator over the values of D"""
  606. return iter(self.values())
  607. def __repr__(self):
  608. """x.__repr__() <==> repr(x)"""
  609. return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key])))
  610. for key in (self.scalars + self.sections)])
  611. __str__ = __repr__
  612. __str__.__doc__ = "x.__str__() <==> str(x)"
  613. # Extra methods - not in a normal dictionary
  614. def dict(self):
  615. """
  616. Return a deepcopy of self as a dictionary.
  617. All members that are ``Section`` instances are recursively turned to
  618. ordinary dictionaries - by calling their ``dict`` method.
  619. >>> n = a.dict()
  620. >>> n == a
  621. 1
  622. >>> n is a
  623. 0
  624. """
  625. newdict = {}
  626. for entry in self:
  627. this_entry = self[entry]
  628. if isinstance(this_entry, Section):
  629. this_entry = this_entry.dict()
  630. elif isinstance(this_entry, list):
  631. # create a copy rather than a reference
  632. this_entry = list(this_entry)
  633. elif isinstance(this_entry, tuple):
  634. # create a copy rather than a reference
  635. this_entry = tuple(this_entry)
  636. newdict[entry] = this_entry
  637. return newdict
  638. def merge(self, indict):
  639. """
  640. A recursive update - useful for merging config files.
  641. >>> a = '''[section1]
  642. ... option1 = True
  643. ... [[subsection]]
  644. ... more_options = False
  645. ... # end of file'''.splitlines()
  646. >>> b = '''# File is user.ini
  647. ... [section1]
  648. ... option1 = False
  649. ... # end of file'''.splitlines()
  650. >>> c1 = ConfigObj(b)
  651. >>> c2 = ConfigObj(a)
  652. >>> c2.merge(c1)
  653. >>> c2
  654. {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
  655. """
  656. for key, val in indict.items():
  657. if (key in self and isinstance(self[key], dict) and
  658. isinstance(val, dict)):
  659. self[key].merge(val)
  660. else:
  661. self[key] = val
  662. def rename(self, oldkey, newkey):
  663. """
  664. Change a keyname to another, without changing position in sequence.
  665. Implemented so that transformations can be made on keys,
  666. as well as on values. (used by encode and decode)
  667. Also renames comments.
  668. """
  669. if oldkey in self.scalars:
  670. the_list = self.scalars
  671. elif oldkey in self.sections:
  672. the_list = self.sections
  673. else:
  674. raise KeyError('Key "%s" not found.' % oldkey)
  675. pos = the_list.index(oldkey)
  676. #
  677. val = self[oldkey]
  678. dict.__delitem__(self, oldkey)
  679. dict.__setitem__(self, newkey, val)
  680. the_list.remove(oldkey)
  681. the_list.insert(pos, newkey)
  682. comm = self.comments[oldkey]
  683. inline_comment = self.inline_comments[oldkey]
  684. del self.comments[oldkey]
  685. del self.inline_comments[oldkey]
  686. self.comments[newkey] = comm
  687. self.inline_comments[newkey] = inline_comment
  688. def walk(self, function, raise_errors=True,
  689. call_on_sections=False, **keywargs):
  690. """
  691. Walk every member and call a function on the keyword and value.
  692. Return a dictionary of the return values
  693. If the function raises an exception, raise the errror
  694. unless ``raise_errors=False``, in which case set the return value to
  695. ``False``.
  696. Any unrecognised keyword arguments you pass to walk, will be pased on
  697. to the function you pass in.
  698. Note: if ``call_on_sections`` is ``True`` then - on encountering a
  699. subsection, *first* the function is called for the *whole* subsection,
  700. and then recurses into it's members. This means your function must be
  701. able to handle strings, dictionaries and lists. This allows you
  702. to change the key of subsections as well as for ordinary members. The
  703. return value when called on the whole subsection has to be discarded.
  704. See the encode and decode methods for examples, including functions.
  705. .. caution::
  706. You can use ``walk`` to transform the names of members of a section
  707. but you mustn't add or delete members.
  708. >>> config = '''[XXXXsection]
  709. ... XXXXkey = XXXXvalue'''.splitlines()
  710. >>> cfg = ConfigObj(config)
  711. >>> cfg
  712. {'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
  713. >>> def transform(section, key):
  714. ... val = section[key]
  715. ... newkey = key.replace('XXXX', 'CLIENT1')
  716. ... section.rename(key, newkey)
  717. ... if isinstance(val, (tuple, list, dict)):
  718. ... pass
  719. ... else:
  720. ... val = val.replace('XXXX', 'CLIENT1')
  721. ... section[newkey] = val
  722. >>> cfg.walk(transform, call_on_sections=True)
  723. {'CLIENT1section': {'CLIENT1key': None}}
  724. >>> cfg
  725. {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}
  726. """
  727. out = {}
  728. # scalars first
  729. for i in range(len(self.scalars)):
  730. entry = self.scalars[i]
  731. try:
  732. val = function(self, entry, **keywargs)
  733. # bound again in case name has changed
  734. entry = self.scalars[i]
  735. out[entry] = val
  736. except Exception:
  737. if raise_errors:
  738. raise
  739. else:
  740. entry = self.scalars[i]
  741. out[entry] = False
  742. # then sections
  743. for i in range(len(self.sections)):
  744. entry = self.sections[i]
  745. if call_on_sections:
  746. try:
  747. function(self, entry, **keywargs)
  748. except Exception:
  749. if raise_errors:
  750. raise
  751. else:
  752. entry = self.sections[i]
  753. out[entry] = False
  754. # bound again in case name has changed
  755. entry = self.sections[i]
  756. # previous result is discarded
  757. out[entry] = self[entry].walk(
  758. function,
  759. raise_errors=raise_errors,
  760. call_on_sections=call_on_sections,
  761. **keywargs)
  762. return out
  763. def decode(self, encoding):
  764. """
  765. Decode all strings and values to unicode, using the specified encoding.
  766. Works with subsections and list values.
  767. Uses the ``walk`` method.
  768. Testing ``encode`` and ``decode``.
  769. >>> m = ConfigObj(a)
  770. >>> m.decode('ascii')
  771. >>> def testuni(val):
  772. ... for entry in val:
  773. ... if not isinstance(entry, unicode):
  774. ... print >> sys.stderr, type(entry)
  775. ... raise AssertionError, 'decode failed.'
  776. ... if isinstance(val[entry], dict):
  777. ... testuni(val[entry])
  778. ... elif not isinstance(val[entry], unicode):
  779. ... raise AssertionError, 'decode failed.'
  780. >>> testuni(m)
  781. >>> m.encode('ascii')
  782. >>> a == m
  783. 1
  784. """
  785. warn('use of ``decode`` is deprecated.', DeprecationWarning)
  786. def decode(section, key, encoding=encoding, warn=True):
  787. """ """
  788. val = section[key]
  789. if isinstance(val, (list, tuple)):
  790. newval = []
  791. for entry in val:
  792. newval.append(entry.decode(encoding))
  793. elif isinstance(val, dict):
  794. newval = val
  795. else:
  796. newval = val.decode(encoding)
  797. newkey = key.decode(encoding)
  798. section.rename(key, newkey)
  799. section[newkey] = newval
  800. # using ``call_on_sections`` allows us to modify section names
  801. self.walk(decode, call_on_sections=True)
  802. def encode(self, encoding):
  803. """
  804. Encode all strings and values from unicode,
  805. using the specified encoding.
  806. Works with subsections and list values.
  807. Uses the ``walk`` method.
  808. """
  809. warn('use of ``encode`` is deprecated.', DeprecationWarning)
  810. def encode(section, key, encoding=encoding):
  811. """ """
  812. val = section[key]
  813. if isinstance(val, (list, tuple)):
  814. newval = []
  815. for entry in val:
  816. newval.append(entry.encode(encoding))
  817. elif isinstance(val, dict):
  818. newval = val
  819. else:
  820. newval = val.encode(encoding)
  821. newkey = key.encode(encoding)
  822. section.rename(key, newkey)
  823. section[newkey] = newval
  824. self.walk(encode, call_on_sections=True)
  825. def istrue(self, key):
  826. """A deprecated version of ``as_bool``."""
  827. warn('use of ``istrue`` is deprecated. Use ``as_bool`` method '
  828. 'instead.', DeprecationWarning)
  829. return self.as_bool(key)
  830. def as_bool(self, key):
  831. """
  832. Accepts a key as input. The corresponding value must be a string or
  833. the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
  834. retain compatibility with Python 2.2.
  835. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
  836. ``True``.
  837. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
  838. ``False``.
  839. ``as_bool`` is not case sensitive.
  840. Any other input will raise a ``ValueError``.
  841. >>> a = ConfigObj()
  842. >>> a['a'] = 'fish'
  843. >>> a.as_bool('a')
  844. Traceback (most recent call last):
  845. ValueError: Value "fish" is neither True nor False
  846. >>> a['b'] = 'True'
  847. >>> a.as_bool('b')
  848. 1
  849. >>> a['b'] = 'off'
  850. >>> a.as_bool('b')
  851. 0
  852. """
  853. val = self[key]
  854. if val == True:
  855. return True
  856. elif val == False:
  857. return False
  858. else:
  859. try:
  860. if not isinstance(val, StringTypes):
  861. # TODO: Why do we raise a KeyError here?
  862. raise KeyError()
  863. else:
  864. return self.main._bools[val.lower()]
  865. except KeyError:
  866. raise ValueError('Value "%s" is neither True nor False' % val)
  867. def as_int(self, key):
  868. """
  869. A convenience method which coerces the specified value to an integer.
  870. If the value is an invalid literal for ``int``, a ``ValueError`` will
  871. be raised.
  872. >>> a = ConfigObj()
  873. >>> a['a'] = 'fish'
  874. >>> a.as_int('a')
  875. Traceback (most recent call last):
  876. ValueError: invalid literal for int(): fish
  877. >>> a['b'] = '1'
  878. >>> a.as_int('b')
  879. 1
  880. >>> a['b'] = '3.2'
  881. >>> a.as_int('b')
  882. Traceback (most recent call last):
  883. ValueError: invalid literal for int(): 3.2
  884. """
  885. return int(self[key])
  886. def as_float(self, key):
  887. """
  888. A convenience method which coerces the specified value to a float.
  889. If the value is an invalid literal for ``float``, a ``ValueError`` will
  890. be raised.
  891. >>> a = ConfigObj()
  892. >>> a['a'] = 'fish'
  893. >>> a.as_float('a')
  894. Traceback (most recent call last):
  895. ValueError: invalid literal for float(): fish
  896. >>> a['b'] = '1'
  897. >>> a.as_float('b')
  898. 1.0
  899. >>> a['b'] = '3.2'
  900. >>> a.as_float('b')
  901. 3.2000000000000002
  902. """
  903. return float(self[key])
  904. def restore_default(self, key):
  905. """
  906. Restore (and return) default value for the specified key.
  907. This method will only work for a ConfigObj that was created
  908. with a configspec and has been validated.
  909. If there is no default value for this key, ``KeyError`` is raised.
  910. """
  911. default = self.default_values[key]
  912. dict.__setitem__(self, key, default)
  913. if key not in self.defaults:
  914. self.defaults.append(key)
  915. return default
  916. def restore_defaults(self):
  917. """
  918. Recursively restore default values to all members
  919. that have them.
  920. This method will only work for a ConfigObj that was created
  921. with a configspec and has been validated.
  922. It doesn't delete or modify entries without default values.
  923. """
  924. for key in self.default_values:
  925. self.restore_default(key)
  926. for section in self.sections:
  927. self[section].restore_defaults()
  928. class ConfigObj(Section):
  929. """An object to read, create, and write config files."""
  930. _keyword = re.compile(r'''^ # line start
  931. (\s*) # indentation
  932. ( # keyword
  933. (?:".*?")| # double quotes
  934. (?:'.*?')| # single quotes
  935. (?:[^'"=].*?) # no quotes
  936. )
  937. \s*=\s* # divider
  938. (.*) # value (including list values and comments)
  939. $ # line end
  940. ''',
  941. re.VERBOSE)
  942. _sectionmarker = re.compile(r'''^
  943. (\s*) # 1: indentation
  944. ((?:\[\s*)+) # 2: section marker open
  945. ( # 3: section name open
  946. (?:"\s*\S.*?\s*")| # at least one non-space with double quotes
  947. (?:'\s*\S.*?\s*')| # at least one non-space with single quotes
  948. (?:[^'"\s].*?) # at least one non-space unquoted
  949. ) # section name close
  950. ((?:\s*\])+) # 4: section marker close
  951. \s*(\#.*)? # 5: optional comment
  952. $''',
  953. re.VERBOSE)
  954. # this regexp pulls list values out as a single string
  955. # or single values and comments
  956. # FIXME: this regex adds a '' to the end of comma terminated lists
  957. # workaround in ``_handle_value``
  958. _valueexp = re.compile(r'''^
  959. (?:
  960. (?:
  961. (
  962. (?:
  963. (?:
  964. (?:".*?")| # double quotes
  965. (?:'.*?')| # single quotes
  966. (?:[^'",\#][^,\#]*?) # unquoted
  967. )
  968. \s*,\s* # comma
  969. )* # match all list items ending in a comma (if any)
  970. )
  971. (
  972. (?:".*?")| # double quotes
  973. (?:'.*?')| # single quotes
  974. (?:[^'",\#\s][^,]*?)| # unquoted
  975. (?:(?<!,)) # Empty value
  976. )? # last item in a list - or string value
  977. )|
  978. (,) # alternatively a single comma - empty list
  979. )
  980. \s*(\#.*)? # optional comment
  981. $''',
  982. re.VERBOSE)
  983. # use findall to get the members of a list value
  984. _listvalueexp = re.compile(r'''
  985. (
  986. (?:".*?")| # double quotes
  987. (?:'.*?')| # single quotes
  988. (?:[^'",\#].*?) # unquoted
  989. )
  990. \s*,\s* # comma
  991. ''',
  992. re.VERBOSE)
  993. # this regexp is used for the value
  994. # when lists are switched off
  995. _nolistvalue = re.compile(r'''^
  996. (
  997. (?:".*?")| # double quotes
  998. (?:'.*?')| # single quotes
  999. (?:[^'"\#].*?)| # unquoted
  1000. (?:) # Empty value
  1001. )
  1002. \s*(\#.*)? # optional comment
  1003. $''',
  1004. re.VERBOSE)
  1005. # regexes for finding triple quoted values on one line
  1006. _single_line_single = re.compile(r"^'''(.*?)'''\s*(#.*)?$")
  1007. _single_line_double = re.compile(r'^"""(.*?)"""\s*(#.*)?$')
  1008. _multi_line_single = re.compile(r"^(.*?)'''\s*(#.*)?$")
  1009. _multi_line_double = re.compile(r'^(.*?)"""\s*(#.*)?$')
  1010. _triple_quote = {
  1011. "'''": (_single_line_single, _multi_line_single),
  1012. '"""': (_single_line_double, _multi_line_double),
  1013. }
  1014. # Used by the ``istrue`` Section method
  1015. _bools = {
  1016. 'yes': True, 'no': False,
  1017. 'on': True, 'off': False,
  1018. '1': True, '0': False,
  1019. 'true': True, 'false': False,
  1020. }
  1021. def __init__(self, infile=None, options=None, **kwargs):
  1022. """
  1023. Parse a config file or create a config file object.
  1024. ``ConfigObj(infile=None, options=None, **kwargs)``
  1025. """
  1026. # init the superclass
  1027. Section.__init__(self, self, 0, self)
  1028. if infile is None:
  1029. infile = []
  1030. if options is None:
  1031. options = {}
  1032. else:
  1033. options = dict(options)
  1034. # keyword arguments take precedence over an options dictionary
  1035. options.update(kwargs)
  1036. defaults = OPTION_DEFAULTS.copy()
  1037. # TODO: check the values too.
  1038. for entry in options:
  1039. if entry not in defaults:
  1040. raise TypeError('Unrecognised option "%s".' % entry)
  1041. # Add any explicit options to the defaults
  1042. defaults.update(options)
  1043. self._initialise(defaults)
  1044. configspec = defaults['configspec']
  1045. self._original_configspec = configspec
  1046. self._load(infile, configspec)
  1047. def _load(self, infile, configspec):
  1048. if isinstance(infile, StringTypes):
  1049. self.filename = infile
  1050. if os.path.isfile(infile):
  1051. h = open(infile, 'rb')
  1052. infile = h.read() or []
  1053. h.close()
  1054. elif self.file_error:
  1055. # raise an error if the file doesn't exist
  1056. raise IOError('Config file not found: "%s".' % self.filename)
  1057. else:
  1058. # file doesn't already exist
  1059. if self.create_empty:
  1060. # this is a good test that the filename specified
  1061. # isn't impossible - like on a non-existent device
  1062. h = open(infile, 'w')
  1063. h.write('')
  1064. h.close()
  1065. infile = []
  1066. elif isinstance(infile, (list, tuple)):
  1067. infile = list(infile)
  1068. elif isinstance(infile, dict):
  1069. # initialise self
  1070. # the Section class handles creating subsections
  1071. if isinstance(infile, ConfigObj):
  1072. # get a copy of our ConfigObj
  1073. infile = infile.dict()
  1074. for entry in infile:
  1075. self[entry] = infile[entry]
  1076. del self._errors
  1077. if configspec is not None:
  1078. self._handle_configspec(configspec)
  1079. else:
  1080. self.configspec = None
  1081. return
  1082. elif hasattr(infile, 'read'):
  1083. # This supports file like objects
  1084. infile = infile.read() or []
  1085. # needs splitting into lines - but needs doing *after* decoding
  1086. # in case it's not an 8 bit encoding
  1087. else:
  1088. raise TypeError('infile must be a filename, file like object, or list of lines.')
  1089. if infile:
  1090. # don't do it for the empty ConfigObj
  1091. infile = self._handle_bom(infile)
  1092. # infile is now *always* a list
  1093. #
  1094. # Set the newlines attribute (first line ending it finds)
  1095. # and strip trailing '\n' or '\r' from lines
  1096. for line in infile:
  1097. if (not line) or (line[-1] not in ('\r', '\n', '\r\n')):
  1098. continue
  1099. for end in ('\r\n', '\n', '\r'):
  1100. if line.endswith(end):
  1101. self.newlines = end
  1102. break
  1103. break
  1104. infile = [line.rstrip('\r\n') for line in infile]
  1105. self._parse(infile)
  1106. # if we had any errors, now is the time to raise them
  1107. if self._errors:
  1108. info = "at line %s." % self._errors[0].line_number
  1109. if len(self._errors) > 1:
  1110. msg = "Parsing failed with several errors.\nFirst error %s" % info
  1111. error = ConfigObjError(msg)
  1112. else:
  1113. error = self._errors[0]
  1114. # set the errors attribute; it's a list of tuples:
  1115. # (error_type, message, line_number)
  1116. error.errors = self._errors
  1117. # set the config attribute
  1118. error.config = self
  1119. raise error
  1120. # delete private attributes
  1121. del self._errors
  1122. if configspec is None:
  1123. self.configspec = None
  1124. else:
  1125. self._handle_configspec(configspec)
  1126. def _initialise(self, options=None):
  1127. if options is None:
  1128. options = OPTION_DEFAULTS
  1129. # initialise a few variables
  1130. self.filename = None
  1131. self._errors = []
  1132. self.raise_errors = options['raise_errors']
  1133. self.interpolation = options['interpolation']
  1134. self.list_values = options['list_values']
  1135. self.create_empty = options['create_empty']
  1136. self.file_error = options['file_error']
  1137. self.stringify = options['stringify']
  1138. self.indent_type = options['indent_type']
  1139. self.encoding = options['encoding']
  1140. self.default_encoding = options['default_encoding']
  1141. self.BOM = False
  1142. self.newlines = None
  1143. self.write_empty_values = options['write_empty_values']
  1144. self.unrepr = options['unrepr']
  1145. self.initial_comment = []
  1146. self.final_comment = []
  1147. self.configspec = {}
  1148. # Clear section attributes as well
  1149. Section._initialise(self)
  1150. def __repr__(self):
  1151. return ('ConfigObj({%s})' %
  1152. ', '.join([('%s: %s' % (repr(key), repr(self[key])))
  1153. for key in (self.scalars + self.sections)]))
  1154. def _handle_bom(self, infile):
  1155. """
  1156. Handle any BOM, and decode if necessary.
  1157. If an encoding is specified, that *must* be used - but the BOM should
  1158. still be removed (and the BOM attribute set).
  1159. (If the encoding is wrongly specified, then a BOM for an alternative
  1160. encoding won't be discovered or removed.)
  1161. If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
  1162. removed. The BOM attribute will be set. UTF16 will be decoded to
  1163. unicode.
  1164. NOTE: This method must not be called with an empty ``infile``.
  1165. Specifying the *wrong* encoding is likely to cause a
  1166. ``UnicodeDecodeError``.
  1167. ``infile`` must always be returned as a list of lines, but may be
  1168. passed in as a single string.
  1169. """
  1170. if ((self.encoding is not None) and
  1171. (self.encoding.lower() not in BOM_LIST)):
  1172. # No need to check for a BOM
  1173. # the encoding specified doesn't have one
  1174. # just decode
  1175. return self._decode(infile, self.encoding)
  1176. if isinstance(infile, (list, tuple)):
  1177. line = infile[0]
  1178. else:
  1179. line = infile
  1180. if self.encoding is not None:
  1181. # encoding explicitly supplied
  1182. # And it could have an associated BOM
  1183. # TODO: if encoding is just UTF16 - we ought to check for both
  1184. # TODO: big endian and little endian versions.
  1185. enc = BOM_LIST[self.encoding.lower()]
  1186. if enc == 'utf_16':
  1187. # For UTF16 we try big endian and little endian
  1188. for BOM, (encoding, final_encoding) in BOMS.items():
  1189. if not final_encoding:
  1190. # skip UTF8
  1191. continue
  1192. if infile.startswith(BOM):
  1193. ### BOM discovered
  1194. ##self.BOM = True
  1195. # Don't need to remove BOM
  1196. return self._decode(infile, encoding)
  1197. # If we get this far, will *probably* raise a DecodeError
  1198. # As it doesn't appear to start with a BOM
  1199. return self._decode(infile, self.encoding)
  1200. # Must be UTF8
  1201. BOM = BOM_SET[enc]
  1202. if not line.startswith(BOM):
  1203. return self._decode(infile, self.encoding)
  1204. newline = line[len(BOM):]
  1205. # BOM removed
  1206. if isinstance(infile, (list, tuple)):
  1207. infile[0] = newline
  1208. else:
  1209. infile = newline
  1210. self.BOM = True
  1211. return self._decode(infile, self.encoding)
  1212. # No encoding specified - so we need to check for UTF8/UTF16
  1213. for BOM, (encoding, final_encoding) in BOMS.items():
  1214. if not line.startswith(BOM):
  1215. continue
  1216. else:
  1217. # BOM discovered
  1218. self.encoding = final_encoding
  1219. if not final_encoding:
  1220. self.BOM = True
  1221. # UTF8
  1222. # remove BOM
  1223. newline = line[len(BOM):]
  1224. if isinstance(infile, (list, tuple)):
  1225. infile[0] = newline
  1226. else:
  1227. infile = newline
  1228. # UTF8 - don't decode
  1229. if isinstance(infile, StringTypes):
  1230. return infile.splitlines(True)
  1231. else:
  1232. return infile
  1233. # UTF16 - have to decode
  1234. return self._decode(infile, encoding)
  1235. # No BOM discovered and no encoding specified, just return
  1236. if isinstance(infile, StringTypes):
  1237. # infile read from a file will be a single string
  1238. return infile.splitlines(True)
  1239. return infile
  1240. def _a_to_u(self, aString):
  1241. """Decode ASCII strings to unicode if a self.encoding is specified."""
  1242. if self.encoding:
  1243. return aString.decode('ascii')
  1244. else:
  1245. return aString
  1246. def _decode(self, infile, encoding):
  1247. """
  1248. Decode infile to unicode. Using the specified encoding.
  1249. if is a string, it also needs converting to a list.
  1250. """
  1251. if isinstance(infile, StringTypes):
  1252. # can't be unicode
  1253. # NOTE: Could raise a ``UnicodeDecodeError``
  1254. return infile.decode(encoding).splitlines(True)
  1255. for i, line in enumerate(infile):
  1256. if not isinstance(line, unicode):

Large files files are truncated, but you can click here to view the full file