PageRenderTime 1864ms CodeModel.GetById 188ms RepoModel.GetById 9ms app.codeStats 0ms

/psychopy/contrib/configobj/__init__.py

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