PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 1ms 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
  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):
  1257. # NOTE: The isinstance test here handles mixed lists of unicode/string
  1258. # NOTE: But the decode will break on any non-string values
  1259. # NOTE: Or could raise a ``UnicodeDecodeError``
  1260. infile[i] = line.decode(encoding)
  1261. return infile
  1262. def _decode_element(self, line):
  1263. """Decode element to unicode if necessary."""
  1264. if not self.encoding:
  1265. return line
  1266. if isinstance(line, str) and self.default_encoding:
  1267. return line.decode(self.default_encoding)
  1268. return line
  1269. def _str(self, value):
  1270. """
  1271. Used by ``stringify`` within validate, to turn non-string values
  1272. into strings.
  1273. """
  1274. if not isinstance(value, StringTypes):
  1275. return str(value)
  1276. else:
  1277. return value
  1278. def _parse(self, infile):
  1279. """Actually parse the config file."""
  1280. temp_list_values = self.list_values
  1281. if self.unrepr:
  1282. self.list_values = False
  1283. comment_list = []
  1284. done_start = False
  1285. this_section = self
  1286. maxline = len(infile) - 1
  1287. cur_index = -1
  1288. reset_comment = False
  1289. while cur_index < maxline:
  1290. if reset_comment:
  1291. comment_list = []
  1292. cur_index += 1
  1293. line = infile[cur_index]
  1294. sline = line.strip()
  1295. # do we have anything on the line ?
  1296. if not sline or sline.startswith('#'):
  1297. reset_comment = False
  1298. comment_list.append(line)
  1299. continue
  1300. if not done_start:
  1301. # preserve initial comment
  1302. self.initial_comment = comment_list
  1303. comment_list = []
  1304. done_start = True
  1305. reset_comment = True
  1306. # first we check if it's a section marker
  1307. mat = self._sectionmarker.match(line)
  1308. if mat is not None:
  1309. # is a section line
  1310. (indent, sect_open, sect_name, sect_close, comment) = mat.groups()
  1311. if indent and (self.indent_type is None):
  1312. self.indent_type = indent
  1313. cur_depth = sect_open.count('[')
  1314. if cur_depth != sect_close.count(']'):
  1315. self._handle_error("Cannot compute the section depth at line %s.",
  1316. NestingError, infile, cur_index)
  1317. continue
  1318. if cur_depth < this_section.depth:
  1319. # the new section is dropping back to a previous level
  1320. try:
  1321. parent = self._match_depth(this_section,
  1322. cur_depth).parent
  1323. except SyntaxError:
  1324. self._handle_error("Cannot compute nesting level at line %s.",
  1325. NestingError, infile, cur_index)
  1326. continue
  1327. elif cur_depth == this_section.depth:
  1328. # the new section is a sibling of the current section
  1329. parent = this_section.parent
  1330. elif cur_depth == this_section.depth + 1:
  1331. # the new section is a child the current section
  1332. parent = this_section
  1333. else:
  1334. self._handle_error("Section too nested at line %s.",
  1335. NestingError, infile, cur_index)
  1336. sect_name = self._unquote(sect_name)
  1337. if parent.has_key(sect_name):
  1338. self._handle_error('Duplicate section name at line %s.',
  1339. DuplicateError, infile, cur_index)
  1340. continue
  1341. # create the new section
  1342. this_section = Section(
  1343. parent,
  1344. cur_depth,
  1345. self,
  1346. name=sect_name)
  1347. parent[sect_name] = this_section
  1348. parent.inline_comments[sect_name] = comment
  1349. parent.comments[sect_name] = comment_list
  1350. continue
  1351. #
  1352. # it's not a section marker,
  1353. # so it should be a valid ``key = value`` line
  1354. mat = self._keyword.match(line)
  1355. if mat is None:
  1356. # it neither matched as a keyword
  1357. # or a section marker
  1358. self._handle_error(
  1359. 'Invalid line at line "%s".',
  1360. ParseError, infile, cur_index)
  1361. else:
  1362. # is a keyword value
  1363. # value will include any inline comment
  1364. (indent, key, value) = mat.groups()
  1365. if indent and (self.indent_type is None):
  1366. self.indent_type = indent
  1367. # check for a multiline value
  1368. if value[:3] in ['"""', "'''"]:
  1369. try:
  1370. (value, comment, cur_index) = self._multiline(
  1371. value, infile, cur_index, maxline)
  1372. except SyntaxError:
  1373. self._handle_error(
  1374. 'Parse error in value at line %s.',
  1375. ParseError, infile, cur_index)
  1376. continue
  1377. else:
  1378. if self.unrepr:
  1379. comment = ''
  1380. try:
  1381. value = unrepr(value)
  1382. except Exception, e:
  1383. if type(e) == UnknownType:
  1384. msg = 'Unknown name or type in value at line %s.'
  1385. else:
  1386. msg = 'Parse error in value at line %s.'
  1387. self._handle_error(msg, UnreprError, infile,
  1388. cur_index)
  1389. continue
  1390. else:
  1391. if self.unrepr:
  1392. comment = ''
  1393. try:
  1394. value = unrepr(value)
  1395. except Exception, e:
  1396. if isinstance(e, UnknownType):
  1397. msg = 'Unknown name or type in value at line %s.'
  1398. else:
  1399. msg = 'Parse error in value at line %s.'
  1400. self._handle_error(msg, UnreprError, infile,
  1401. cur_index)
  1402. continue
  1403. else:
  1404. # extract comment and lists
  1405. try:
  1406. (value, comment) = self._handle_value(value)
  1407. except SyntaxError:
  1408. self._handle_error(
  1409. 'Parse error in value at line %s.',
  1410. ParseError, infile, cur_index)
  1411. continue
  1412. #
  1413. key = self._unquote(key)
  1414. if this_section.has_key(key):
  1415. self._handle_error(
  1416. 'Duplicate keyword name at line %s.',
  1417. DuplicateError, infile, cur_index)
  1418. continue
  1419. # add the key.
  1420. # we set unrepr because if we have got this far we will never
  1421. # be creating a new section
  1422. this_section.__setitem__(key, value, unrepr=True)
  1423. this_section.inline_comments[key] = comment
  1424. this_section.comments[key] = comment_list
  1425. continue
  1426. #
  1427. if self.indent_type is None:
  1428. # no indentation used, set the type accordingly
  1429. self.indent_type = ''
  1430. # preserve the final comment
  1431. if not self and not self.initial_comment:
  1432. self.initial_comment = comment_list
  1433. elif not reset_comment:
  1434. self.final_comment = comment_list
  1435. self.list_values = temp_list_values
  1436. def _match_depth(self, sect, depth):
  1437. """
  1438. Given a section and a depth level, walk back through the sections
  1439. parents to see if the depth level matches a previous section.
  1440. Return a reference to the right section,
  1441. or raise a SyntaxError.
  1442. """
  1443. while depth < sect.depth:
  1444. if sect is sect.parent:
  1445. # we've reached the top level already
  1446. raise SyntaxError()
  1447. sect = sect.parent
  1448. if sect.depth == depth:
  1449. return sect
  1450. # shouldn't get here
  1451. raise SyntaxError()
  1452. def _handle_error(self, text, ErrorClass, infile, cur_index):
  1453. """
  1454. Handle an error according to the error settings.
  1455. Either raise the error or store it.
  1456. The error will have occured at ``cur_index``
  1457. """
  1458. line = infile[cur_index]
  1459. cur_index += 1
  1460. message = text % cur_index
  1461. error = ErrorClass(message, cur_index, line)
  1462. if self.raise_errors:
  1463. # raise the error - parsing stops here
  1464. raise error
  1465. # store the error
  1466. # reraise when parsing has finished
  1467. self._errors.append(error)
  1468. def _unquote(self, value):
  1469. """Return an unquoted version of a value"""
  1470. if (value[0] == value[-1]) and (value[0] in ('"', "'")):
  1471. value = value[1:-1]
  1472. return value
  1473. def _quote(self, value, multiline=True):
  1474. """
  1475. Return a safely quoted version of a value.
  1476. Raise a ConfigObjError if the value cannot be safely quoted.
  1477. If multiline is ``True`` (default) then use triple quotes
  1478. if necessary.
  1479. Don't quote values that don't need it.
  1480. Recursively quote members of a list and return a comma joined list.
  1481. Multiline is ``False`` for lists.
  1482. Obey list syntax for empty and single member lists.
  1483. If ``list_values=False`` then the value is only quoted if it contains
  1484. a ``\n`` (is multiline) or '#'.
  1485. If ``write_empty_values`` is set, and the value is an empty string, it
  1486. won't be quoted.
  1487. """
  1488. if multiline and self.write_empty_values and value == '':
  1489. # Only if multiline is set, so that it is used for values not
  1490. # keys, and not values that are part of a list
  1491. return ''
  1492. if multiline and isinstance(value, (list, tuple)):
  1493. if not value:
  1494. return ','
  1495. elif len(value) == 1:
  1496. return self._quote(value[0], multiline=False) + ','
  1497. return ', '.join([self._quote(val, multiline=False)
  1498. for val in value])
  1499. if not isinstance(value, StringTypes):
  1500. if self.stringify:
  1501. value = str(value)
  1502. else:
  1503. raise TypeError('Value "%s" is not a string.' % value)
  1504. if not value:
  1505. return '""'
  1506. no_lists_no_quotes = not self.list_values and '\n' not in value and '#' not in value
  1507. need_triple = multiline and ((("'" in value) and ('"' in value)) or ('\n' in value ))
  1508. hash_triple_quote = multiline and not need_triple and ("'" in value) and ('"' in value) and ('#' in value)
  1509. check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote
  1510. if check_for_single:
  1511. if not self.list_values:
  1512. # we don't quote if ``list_values=False``
  1513. quot = noquot
  1514. # for normal values either single or double quotes will do
  1515. elif '\n' in value:
  1516. # will only happen if multiline is off - e.g. '\n' in key
  1517. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1518. elif ((value[0] not in wspace_plus) and
  1519. (value[-1] not in wspace_plus) and
  1520. (',' not in value)):
  1521. quot = noquot
  1522. else:
  1523. quot = self._get_single_quote(value)
  1524. else:
  1525. # if value has '\n' or "'" *and* '"', it will need triple quotes
  1526. quot = self._get_triple_quote(value)
  1527. if quot == noquot and '#' in value and self.list_values:
  1528. quot = self._get_single_quote(value)
  1529. return quot % value
  1530. def _get_single_quote(self, value):
  1531. if ("'" in value) and ('"' in value):
  1532. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1533. elif '"' in value:
  1534. quot = squot
  1535. else:
  1536. quot = dquot
  1537. return quot
  1538. def _get_triple_quote(self, value):
  1539. if (value.find('"""') != -1) and (value.find("'''") != -1):
  1540. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1541. if value.find('"""') == -1:
  1542. quot = tdquot
  1543. else:
  1544. quot = tsquot
  1545. return quot
  1546. def _handle_value(self, value):
  1547. """
  1548. Given a value string, unquote, remove comment,
  1549. handle lists. (including empty and single member lists)
  1550. """
  1551. # do we look for lists in values ?
  1552. if not self.list_values:
  1553. mat = self._nolistvalue.match(value)
  1554. if mat is None:
  1555. raise SyntaxError()
  1556. # NOTE: we don't unquote here
  1557. return mat.groups()
  1558. #
  1559. mat = self._valueexp.match(value)
  1560. if mat is None:
  1561. # the value is badly constructed, probably badly quoted,
  1562. # or an invalid list
  1563. raise SyntaxError()
  1564. (list_values, single, empty_list, comment) = mat.groups()
  1565. if (list_values == '') and (single is None):
  1566. # change this if you want to accept empty values
  1567. raise SyntaxError()
  1568. # NOTE: note there is no error handling from here if the regex
  1569. # is wrong: then incorrect values will slip through
  1570. if empty_list is not None:
  1571. # the single comma - meaning an empty list
  1572. return ([], comment)
  1573. if single is not None:
  1574. # handle empty values
  1575. if list_values and not single:
  1576. # FIXME: the '' is a workaround because our regex now matches
  1577. # '' at the end of a list if it has a trailing comma
  1578. single = None
  1579. else:
  1580. single = single or '""'
  1581. single = self._unquote(single)
  1582. if list_values == '':
  1583. # not a list value
  1584. return (single, comment)
  1585. the_list = self._listvalueexp.findall(list_values)
  1586. the_list = [self._unquote(val) for val in the_list]
  1587. if single is not None:
  1588. the_list += [single]
  1589. return (the_list, comment)
  1590. def _multiline(self, value, infile, cur_index, maxline):
  1591. """Extract the value, where we are in a multiline situation."""
  1592. quot = value[:3]
  1593. newvalue = value[3:]
  1594. single_line = self._triple_quote[quot][0]
  1595. multi_line = self._triple_quote[quot][1]
  1596. mat = single_line.match(value)
  1597. if mat is not None:
  1598. retval = list(mat.groups())
  1599. retval.append(cur_index)
  1600. return retval
  1601. elif newvalue.find(quot) != -1:
  1602. # somehow the triple quote is missing
  1603. raise SyntaxError()
  1604. #
  1605. while cur_index < maxline:
  1606. cur_index += 1
  1607. newvalue += '\n'
  1608. line = infile[cur_index]
  1609. if line.find(quot) == -1:
  1610. newvalue += line
  1611. else:
  1612. # end of multiline, process it
  1613. break
  1614. else:
  1615. # we've got to the end of the config, oops...
  1616. raise SyntaxError()
  1617. mat = multi_line.match(line)
  1618. if mat is None:
  1619. # a badly formed line
  1620. raise SyntaxError()
  1621. (value, comment) = mat.groups()
  1622. return (newvalue + value, comment, cur_index)
  1623. def _handle_configspec(self, configspec):
  1624. """Parse the configspec."""
  1625. # FIXME: Should we check that the configspec was created with the
  1626. # correct settings ? (i.e. ``list_values=False``)
  1627. if not isinstance(configspec, ConfigObj):
  1628. try:
  1629. configspec = ConfigObj(configspec,
  1630. raise_errors=True,
  1631. file_error=True,
  1632. list_values=False)
  1633. except ConfigObjError, e:
  1634. # FIXME: Should these errors have a reference
  1635. # to the already parsed ConfigObj ?
  1636. raise ConfigspecError('Parsing configspec failed: %s' % e)
  1637. except IOError, e:
  1638. raise IOError('Reading configspec failed: %s' % e)
  1639. self._set_configspec_value(configspec, self)
  1640. def _set_configspec_value(self, configspec, section):
  1641. """Used to recursively set configspec values."""
  1642. if '__many__' in configspec.sections:
  1643. section.configspec['__many__'] = configspec['__many__']
  1644. if len(configspec.sections) > 1:
  1645. # FIXME: can we supply any useful information here ?
  1646. raise RepeatSectionError()
  1647. if hasattr(configspec, 'initial_comment'):
  1648. section._configspec_initial_comment = configspec.initial_comment
  1649. section._configspec_final_comment = configspec.final_comment
  1650. section._configspec_encoding = configspec.encoding
  1651. section._configspec_BOM = configspec.BOM
  1652. section._configspec_newlines = configspec.newlines
  1653. section._configspec_indent_type = configspec.indent_type
  1654. for entry in configspec.scalars:
  1655. section._configspec_comments[entry] = configspec.comments[entry]
  1656. section._configspec_inline_comments[entry] = configspec.inline_comments[entry]
  1657. section.configspec[entry] = configspec[entry]
  1658. section._order.append(entry)
  1659. for entry in configspec.sections:
  1660. if entry == '__many__':
  1661. continue
  1662. section._cs_section_comments[entry] = configspec.comments[entry]
  1663. section._cs_section_inline_comments[entry] = configspec.inline_comments[entry]
  1664. if not section.has_key(entry):
  1665. section[entry] = {}
  1666. self._set_configspec_value(configspec[entry], section[entry])
  1667. def _handle_repeat(self, section, configspec):
  1668. """Dynamically assign configspec for repeated section."""
  1669. try:
  1670. section_keys = configspec.sections
  1671. scalar_keys = configspec.scalars
  1672. except AttributeError:
  1673. section_keys = [entry for entry in configspec
  1674. if isinstance(configspec[entry], dict)]
  1675. scalar_keys = [entry for entry in configspec
  1676. if not isinstance(configspec[entry], dict)]
  1677. if '__many__' in section_keys and len(section_keys) > 1:
  1678. # FIXME: can we supply any useful information here ?
  1679. raise RepeatSectionError()
  1680. scalars = {}
  1681. sections = {}
  1682. for entry in scalar_keys:
  1683. val = configspec[entry]
  1684. scalars[entry] = val
  1685. for entry in section_keys:
  1686. val = configspec[entry]
  1687. if entry == '__many__':
  1688. scalars[entry] = val
  1689. continue
  1690. sections[entry] = val
  1691. section.configspec = scalars
  1692. for entry in sections:
  1693. if not section.has_key(entry):
  1694. section[entry] = {}
  1695. self._handle_repeat(section[entry], sections[entry])
  1696. def _write_line(self, indent_string, entry, this_entry, comment):
  1697. """Write an individual line, for the write method"""
  1698. # NOTE: the calls to self._quote here handles non-StringType values.
  1699. if not self.unrepr:
  1700. val = self._decode_element(self._quote(this_entry))
  1701. else:
  1702. val = repr(this_entry)
  1703. return '%s%s%s%s%s' % (indent_string,
  1704. self._decode_element(self._quote(entry, multiline=False)),
  1705. self._a_to_u(' = '),
  1706. val,
  1707. self._decode_element(comment))
  1708. def _write_marker(self, indent_string, depth, entry, comment):
  1709. """Write a section marker line"""
  1710. return '%s%s%s%s%s' % (indent_string,
  1711. self._a_to_u('[' * depth),
  1712. self._quote(self._decode_element(entry), multiline=False),
  1713. self._a_to_u(']' * depth),
  1714. self._decode_element(comment))
  1715. def _handle_comment(self, comment):
  1716. """Deal with a comment."""
  1717. if not comment:
  1718. return ''
  1719. start = self.indent_type
  1720. if not comment.startswith('#'):
  1721. start += self._a_to_u(' # ')
  1722. return (start + comment)
  1723. # Public methods
  1724. def write(self, outfile=None, section=None):
  1725. """
  1726. Write the current ConfigObj as a file
  1727. tekNico: FIXME: use StringIO instead of real files
  1728. >>> filename = a.filename
  1729. >>> a.filename = 'test.ini'
  1730. >>> a.write()
  1731. >>> a.filename = filename
  1732. >>> a == ConfigObj('test.ini', raise_errors=True)
  1733. 1
  1734. """
  1735. if self.indent_type is None:
  1736. # this can be true if initialised from a dictionary
  1737. self.indent_type = DEFAULT_INDENT_TYPE
  1738. out = []
  1739. cs = self._a_to_u('#')
  1740. csp = self._a_to_u('# ')
  1741. if section is None:
  1742. int_val = self.interpolation
  1743. self.interpolation = False
  1744. section = self
  1745. for line in self.initial_comment:
  1746. line = self._decode_element(line)
  1747. stripped_line = line.strip()
  1748. if stripped_line and not stripped_line.startswith(cs):
  1749. line = csp + line
  1750. out.append(line)
  1751. indent_string = self.indent_type * section.depth
  1752. for entry in (section.scalars + section.sections):
  1753. if entry in section.defaults:
  1754. # don't write out default values
  1755. continue
  1756. for comment_line in section.comments[entry]:
  1757. comment_line = self._decode_element(comment_line.lstrip())
  1758. if comment_line and not comment_line.startswith(cs):
  1759. comment_line = csp + comment_line
  1760. out.append(indent_string + comment_line)
  1761. this_entry = section[entry]
  1762. comment = self._handle_comment(section.inline_comments[entry])
  1763. if isinstance(this_entry, dict):
  1764. # a section
  1765. out.append(self._write_marker(
  1766. indent_string,
  1767. this_entry.depth,
  1768. entry,
  1769. comment))
  1770. out.extend(self.write(section=this_entry))
  1771. else:
  1772. out.append(self._write_line(
  1773. indent_string,
  1774. entry,
  1775. this_entry,
  1776. comment))
  1777. if section is self:
  1778. for line in self.final_comment:
  1779. line = self._decode_element(line)
  1780. stripped_line = line.strip()
  1781. if stripped_line and not stripped_line.startswith(cs):
  1782. line = csp + line
  1783. out.append(line)
  1784. self.interpolation = int_val
  1785. if section is not self:
  1786. return out
  1787. if (self.filename is None) and (outfile is None):
  1788. # output a list of lines
  1789. # might need to encode
  1790. # NOTE: This will *screw* UTF16, each line will start with the BOM
  1791. if self.encoding:
  1792. out = [l.encode(self.encoding) for l in out]
  1793. if (self.BOM and ((self.encoding is None) or
  1794. (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
  1795. # Add the UTF8 BOM
  1796. if not out:
  1797. out.append('')
  1798. out[0] = BOM_UTF8 + out[0]
  1799. return out
  1800. # Turn the list to a string, joined with correct newlines
  1801. newline = self.newlines or os.linesep
  1802. output = self._a_to_u(newline).join(out)
  1803. if self.encoding:
  1804. output = output.encode(self.encoding)
  1805. if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)):
  1806. # Add the UTF8 BOM
  1807. output = BOM_UTF8 + output
  1808. if not output.endswith(newline):
  1809. output += newline
  1810. if outfile is not None:
  1811. outfile.write(output)
  1812. else:
  1813. h = open(self.filename, 'wb')
  1814. h.write(output)
  1815. h.close()
  1816. def validate(self, validator, preserve_errors=False, copy=False,
  1817. section=None):
  1818. """
  1819. Test the ConfigObj against a configspec.
  1820. It uses the ``validator`` object from *validate.py*.
  1821. To run ``validate`` on the current ConfigObj, call: ::
  1822. test = config.validate(validator)
  1823. (Normally having previously passed in the configspec when the ConfigObj
  1824. was created - you can dynamically assign a dictionary of checks to the
  1825. ``configspec`` attribute of a section though).
  1826. It returns ``True`` if everything passes, or a dictionary of
  1827. pass/fails (True/False). If every member of a subsection passes, it
  1828. will just have the value ``True``. (It also returns ``False`` if all
  1829. members fail).
  1830. In addition, it converts the values from strings to their native
  1831. types if their checks pass (and ``stringify`` is set).
  1832. If ``preserve_errors`` is ``True`` (``False`` is default) then instead
  1833. of a marking a fail with a ``False``, it will preserve the actual
  1834. exception object. This can contain info about the reason for failure.
  1835. For example the ``VdtValueTooSmallError`` indicates that the value
  1836. supplied was too small. If a value (or section) is missing it will
  1837. still be marked as ``False``.
  1838. You must have the validate module to use ``preserve_errors=True``.
  1839. You can then use the ``flatten_errors`` function to turn your nested
  1840. results dictionary into a flattened list of failures - useful for
  1841. displaying meaningful error messages.
  1842. """
  1843. if section is None:
  1844. if self.configspec is None:
  1845. raise ValueError('No configspec supplied.')
  1846. if preserve_errors:
  1847. # We do this once to remove a top level dependency on the validate module
  1848. # Which makes importing configobj faster
  1849. from validate import VdtMissingValue
  1850. self._vdtMissingValue = VdtMissingValue
  1851. section = self
  1852. #
  1853. spec_section = section.configspec
  1854. if copy and hasattr(section, '_configspec_initial_comment'):
  1855. section.initial_comment = section._configspec_initial_comment
  1856. section.final_comment = section._configspec_final_comment
  1857. section.encoding = section._configspec_encoding
  1858. section.BOM = section._configspec_BOM
  1859. section.newlines = section._configspec_newlines
  1860. section.indent_type = section._configspec_indent_type
  1861. if '__many__' in section.configspec:
  1862. many = spec_section['__many__']
  1863. # dynamically assign the configspecs
  1864. # for the sections below
  1865. for entry in section.sections:
  1866. self._handle_repeat(section[entry], many)
  1867. #
  1868. out = {}
  1869. ret_true = True
  1870. ret_false = True
  1871. order = [k for k in section._order if k in spec_section]
  1872. order += [k for k in spec_section if k not in order]
  1873. for entry in order:
  1874. if entry == '__many__':
  1875. continue
  1876. if (not entry in section.scalars) or (entry in section.defaults):
  1877. # missing entries
  1878. # or entries from defaults
  1879. missing = True
  1880. val = None
  1881. if copy and not entry in section.scalars:
  1882. # copy comments
  1883. section.comments[entry] = (
  1884. section._configspec_comments.get(entry, []))
  1885. section.inline_comments[entry] = (
  1886. section._configspec_inline_comments.get(entry, ''))
  1887. #
  1888. else:
  1889. missing = False
  1890. val = section[entry]
  1891. try:
  1892. check = validator.check(spec_section[entry],
  1893. val,
  1894. missing=missing
  1895. )
  1896. except validator.baseErrorClass, e:
  1897. if not preserve_errors or isinstance(e, self._vdtMissingValue):
  1898. out[entry] = False
  1899. else:
  1900. # preserve the error
  1901. out[entry] = e
  1902. ret_false = False
  1903. ret_true = False
  1904. else:
  1905. try:
  1906. section.default_values.pop(entry, None)
  1907. except AttributeError:
  1908. # For Python 2.2 compatibility
  1909. try:
  1910. del section.default_values[entry]
  1911. except KeyError:
  1912. pass
  1913. if hasattr(validator, 'get_default_value'):
  1914. try:
  1915. section.default_values[entry] = validator.get_default_value(spec_section[entry])
  1916. except KeyError:
  1917. # No default
  1918. pass
  1919. ret_false = False
  1920. out[entry] = True
  1921. if self.stringify or missing:
  1922. # if we are doing type conversion
  1923. # or the value is a supplied default
  1924. if not self.stringify:
  1925. if isinstance(check, (list, tuple)):
  1926. # preserve lists
  1927. check = [self._str(item) for item in check]
  1928. elif missing and check is None:
  1929. # convert the None from a default to a ''
  1930. check = ''
  1931. else:
  1932. check = self._str(check)
  1933. if (check != val) or missing:
  1934. section[entry] = check
  1935. if not copy and missing and entry not in section.defaults:
  1936. section.defaults.append(entry)
  1937. # Missing sections will have been created as empty ones when the
  1938. # configspec was read.
  1939. for entry in section.sections:
  1940. # FIXME: this means DEFAULT is not copied in copy mode
  1941. if section is self and entry == 'DEFAULT':
  1942. continue
  1943. if copy:
  1944. section.comments[entry] = section._cs_section_comments.get(entry, [])
  1945. section.inline_comments[entry] = section._cs_section_inline_comments.get(entry, '')
  1946. check = self.validate(validator, preserve_errors=preserve_errors, copy=copy, section=section[entry])
  1947. out[entry] = check
  1948. if check == False:
  1949. ret_true = False
  1950. elif check == True:
  1951. ret_false = False
  1952. else:
  1953. ret_true = False
  1954. ret_false = False
  1955. #
  1956. if ret_true:
  1957. return True
  1958. elif ret_false:
  1959. return False
  1960. return out
  1961. def reset(self):
  1962. """Clear ConfigObj instance and restore to 'freshly created' state."""
  1963. self.clear()
  1964. self._initialise()
  1965. # FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
  1966. # requires an empty dictionary
  1967. self.configspec = None
  1968. # Just to be sure ;-)
  1969. self._original_configspec = None
  1970. def reload(self):
  1971. """
  1972. Reload a ConfigObj from file.
  1973. This method raises a ``ReloadError`` if the ConfigObj doesn't have
  1974. a filename attribute pointing to a file.
  1975. """
  1976. if not isinstance(self.filename, StringTypes):
  1977. raise ReloadError()
  1978. filename = self.filename
  1979. current_options = {}
  1980. for entry in OPTION_DEFAULTS:
  1981. if entry == 'configspec':
  1982. continue
  1983. current_options[entry] = getattr(self, entry)
  1984. configspec = self._original_configspec
  1985. current_options['configspec'] = configspec
  1986. self.clear()
  1987. self._initialise(current_options)
  1988. self._load(filename, configspec)
  1989. class SimpleVal(object):
  1990. """
  1991. A simple validator.
  1992. Can be used to check that all members expected are present.
  1993. To use it, provide a configspec with all your members in (the value given
  1994. will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
  1995. method of your ``ConfigObj``. ``validate`` will return ``True`` if all
  1996. members are present, or a dictionary with True/False meaning
  1997. present/missing. (Whole missing sections will be replaced with ``False``)
  1998. """
  1999. def __init__(self):
  2000. self.baseErrorClass = ConfigObjError
  2001. def check(self, check, member, missing=False):
  2002. """A dummy check method, always returns the value unchanged."""
  2003. if missing:
  2004. raise self.baseErrorClass()
  2005. return member
  2006. # Check / processing functions for options
  2007. def flatten_errors(cfg, res, levels=None, results=None):
  2008. """
  2009. An example function that will turn a nested dictionary of results
  2010. (as returned by ``ConfigObj.validate``) into a flat list.
  2011. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
  2012. dictionary returned by ``validate``.
  2013. (This is a recursive function, so you shouldn't use the ``levels`` or
  2014. ``results`` arguments - they are used by the function.
  2015. Returns a list of keys that failed. Each member of the list is a tuple :
  2016. ::
  2017. ([list of sections...], key, result)
  2018. If ``validate`` was called with ``preserve_errors=False`` (the default)
  2019. then ``result`` will always be ``False``.
  2020. *list of sections* is a flattened list of sections that the key was found
  2021. in.
  2022. If the section was missing then key will be ``None``.
  2023. If the value (or section) was missing then ``result`` will be ``False``.
  2024. If ``validate`` was called with ``preserve_errors=True`` and a value
  2025. was present, but failed the check, then ``result`` will be the exception
  2026. object returned. You can use this as a string that describes the failure.
  2027. For example *The value "3" is of the wrong type*.
  2028. >>> import validate
  2029. >>> vtor = validate.Validator()
  2030. >>> my_ini = '''
  2031. ... option1 = True
  2032. ... [section1]
  2033. ... option1 = True
  2034. ... [section2]
  2035. ... another_option = Probably
  2036. ... [section3]
  2037. ... another_option = True
  2038. ... [[section3b]]
  2039. ... value = 3
  2040. ... value2 = a
  2041. ... value3 = 11
  2042. ... '''
  2043. >>> my_cfg = '''
  2044. ... option1 = boolean()
  2045. ... option2 = boolean()
  2046. ... option3 = boolean(default=Bad_value)
  2047. ... [section1]
  2048. ... option1 = boolean()
  2049. ... option2 = boolean()
  2050. ... option3 = boolean(default=Bad_value)
  2051. ... [section2]
  2052. ... another_option = boolean()
  2053. ... [section3]
  2054. ... another_option = boolean()
  2055. ... [[section3b]]
  2056. ... value = integer
  2057. ... value2 = integer
  2058. ... value3 = integer(0, 10)
  2059. ... [[[section3b-sub]]]
  2060. ... value = string
  2061. ... [section4]
  2062. ... another_option = boolean()
  2063. ... '''
  2064. >>> cs = my_cfg.split('\\n')
  2065. >>> ini = my_ini.split('\\n')
  2066. >>> cfg = ConfigObj(ini, configspec=cs)
  2067. >>> res = cfg.validate(vtor, preserve_errors=True)
  2068. >>> errors = []
  2069. >>> for entry in flatten_errors(cfg, res):
  2070. ... section_list, key, error = entry
  2071. ... section_list.insert(0, '[root]')
  2072. ... if key is not None:
  2073. ... section_list.append(key)
  2074. ... else:
  2075. ... section_list.append('[missing]')
  2076. ... section_string = ', '.join(section_list)
  2077. ... errors.append((section_string, ' = ', error))
  2078. >>> errors.sort()
  2079. >>> for entry in errors:
  2080. ... print entry[0], entry[1], (entry[2] or 0)
  2081. [root], option2 = 0
  2082. [root], option3 = the value "Bad_value" is of the wrong type.
  2083. [root], section1, option2 = 0
  2084. [root], section1, option3 = the value "Bad_value" is of the wrong type.
  2085. [root], section2, another_option = the value "Probably" is of the wrong type.
  2086. [root], section3, section3b, section3b-sub, [missing] = 0
  2087. [root], section3, section3b, value2 = the value "a" is of the wrong type.
  2088. [root], section3, section3b, value3 = the value "11" is too big.
  2089. [root], section4, [missing] = 0
  2090. """
  2091. if levels is None:
  2092. # first time called
  2093. levels = []
  2094. results = []
  2095. if res is True:
  2096. return results
  2097. if res is False:
  2098. results.append((levels[:], None, False))
  2099. if levels:
  2100. levels.pop()
  2101. return results
  2102. for (key, val) in res.items():
  2103. if val == True:
  2104. continue
  2105. if isinstance(cfg.get(key), dict):
  2106. # Go down one level
  2107. levels.append(key)
  2108. flatten_errors(cfg[key], val, levels, results)
  2109. continue
  2110. results.append((levels[:], key, val))
  2111. #
  2112. # Go up one level
  2113. if levels:
  2114. levels.pop()
  2115. #
  2116. return results
  2117. """*A programming language is a medium of expression.* - Paul Graham"""