PageRenderTime 59ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/config/configobj.py

https://bitbucket.org/soko/mozilla-central
Python | 2279 lines | 2188 code | 37 blank | 54 comment | 27 complexity | 74f5db3113222f5b979f0ee9311ef17c MD5 | raw file
Possible License(s): GPL-2.0, JSON, 0BSD, LGPL-3.0, AGPL-1.0, MIT, MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.1, Apache-2.0

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

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

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