configobj.py 82 KB

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