configobj.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  1. # configobj.py
  2. # A config file reader/writer that supports nested sections in config files.
  3. # Copyright (C) 2005-2010 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 os
  17. import re
  18. import sys
  19. from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
  20. # imported lazily to avoid startup performance hit if it isn't used
  21. compiler = None
  22. # A dictionary mapping BOM to
  23. # the encoding to decode with, and what to set the
  24. # encoding attribute to.
  25. BOMS = {
  26. BOM_UTF8: ('utf_8', None),
  27. BOM_UTF16_BE: ('utf16_be', 'utf_16'),
  28. BOM_UTF16_LE: ('utf16_le', 'utf_16'),
  29. BOM_UTF16: ('utf_16', 'utf_16'),
  30. }
  31. # All legal variants of the BOM codecs.
  32. # TODO: the list of aliases is not meant to be exhaustive, is there a
  33. # better way ?
  34. BOM_LIST = {
  35. 'utf_16': 'utf_16',
  36. 'u16': 'utf_16',
  37. 'utf16': 'utf_16',
  38. 'utf-16': 'utf_16',
  39. 'utf16_be': 'utf16_be',
  40. 'utf_16_be': 'utf16_be',
  41. 'utf-16be': 'utf16_be',
  42. 'utf16_le': 'utf16_le',
  43. 'utf_16_le': 'utf16_le',
  44. 'utf-16le': 'utf16_le',
  45. 'utf_8': 'utf_8',
  46. 'u8': 'utf_8',
  47. 'utf': 'utf_8',
  48. 'utf8': 'utf_8',
  49. 'utf-8': 'utf_8',
  50. }
  51. # Map of encodings to the BOM to write.
  52. BOM_SET = {
  53. 'utf_8': BOM_UTF8,
  54. 'utf_16': BOM_UTF16,
  55. 'utf16_be': BOM_UTF16_BE,
  56. 'utf16_le': BOM_UTF16_LE,
  57. None: BOM_UTF8
  58. }
  59. def match_utf8(encoding):
  60. return BOM_LIST.get(encoding.lower()) == 'utf_8'
  61. # Quote strings used for writing values
  62. squot = "'%s'"
  63. dquot = '"%s"'
  64. noquot = "%s"
  65. wspace_plus = ' \r\n\v\t\'"'
  66. tsquot = '"""%s"""'
  67. tdquot = "'''%s'''"
  68. # Sentinel for use in getattr calls to replace hasattr
  69. MISSING = object()
  70. __version__ = '4.7.2'
  71. try:
  72. any
  73. except NameError:
  74. def any(iterable):
  75. for entry in iterable:
  76. if entry:
  77. return True
  78. return False
  79. __all__ = (
  80. '__version__',
  81. 'DEFAULT_INDENT_TYPE',
  82. 'DEFAULT_INTERPOLATION',
  83. 'ConfigObjError',
  84. 'NestingError',
  85. 'ParseError',
  86. 'DuplicateError',
  87. 'ConfigspecError',
  88. 'ConfigObj',
  89. 'SimpleVal',
  90. 'InterpolationError',
  91. 'InterpolationLoopError',
  92. 'MissingInterpolationOption',
  93. 'RepeatSectionError',
  94. 'ReloadError',
  95. 'UnreprError',
  96. 'UnknownType',
  97. 'flatten_errors',
  98. 'get_extra_values'
  99. )
  100. DEFAULT_INTERPOLATION = 'configparser'
  101. DEFAULT_INDENT_TYPE = ' '
  102. MAX_INTERPOL_DEPTH = 10
  103. OPTION_DEFAULTS = {
  104. 'interpolation': True,
  105. 'raise_errors': False,
  106. 'list_values': True,
  107. 'create_empty': False,
  108. 'file_error': False,
  109. 'configspec': None,
  110. 'stringify': True,
  111. # option may be set to one of ('', ' ', '\t')
  112. 'indent_type': None,
  113. 'encoding': None,
  114. 'default_encoding': None,
  115. 'unrepr': False,
  116. 'write_empty_values': False,
  117. }
  118. def getObj(s):
  119. global compiler
  120. if compiler is None:
  121. import compiler
  122. s = "a=" + s
  123. p = compiler.parse(s)
  124. return p.getChildren()[1].getChildren()[0].getChildren()[1]
  125. class UnknownType(Exception):
  126. pass
  127. class Builder(object):
  128. def build(self, o):
  129. m = getattr(self, 'build_' + o.__class__.__name__, None)
  130. if m is None:
  131. raise UnknownType(o.__class__.__name__)
  132. return m(o)
  133. def build_List(self, o):
  134. return map(self.build, o.getChildren())
  135. def build_Const(self, o):
  136. return o.value
  137. def build_Dict(self, o):
  138. d = {}
  139. i = iter(map(self.build, o.getChildren()))
  140. for el in i:
  141. d[el] = i.next()
  142. return d
  143. def build_Tuple(self, o):
  144. return tuple(self.build_List(o))
  145. def build_Name(self, o):
  146. if o.name == 'None':
  147. return None
  148. if o.name == 'True':
  149. return True
  150. if o.name == 'False':
  151. return False
  152. # An undefined Name
  153. raise UnknownType('Undefined Name')
  154. def build_Add(self, o):
  155. real, imag = map(self.build_Const, o.getChildren())
  156. try:
  157. real = float(real)
  158. except TypeError:
  159. raise UnknownType('Add')
  160. if not isinstance(imag, complex) or imag.real != 0.0:
  161. raise UnknownType('Add')
  162. return real+imag
  163. def build_Getattr(self, o):
  164. parent = self.build(o.expr)
  165. return getattr(parent, o.attrname)
  166. def build_UnarySub(self, o):
  167. return -self.build_Const(o.getChildren()[0])
  168. def build_UnaryAdd(self, o):
  169. return self.build_Const(o.getChildren()[0])
  170. _builder = Builder()
  171. def unrepr(s):
  172. if not s:
  173. return s
  174. return _builder.build(getObj(s))
  175. class ConfigObjError(SyntaxError):
  176. """
  177. This is the base class for all errors that ConfigObj raises.
  178. It is a subclass of SyntaxError.
  179. """
  180. def __init__(self, message='', line_number=None, line=''):
  181. self.line = line
  182. self.line_number = line_number
  183. SyntaxError.__init__(self, message)
  184. class NestingError(ConfigObjError):
  185. """
  186. This error indicates a level of nesting that doesn't match.
  187. """
  188. class ParseError(ConfigObjError):
  189. """
  190. This error indicates that a line is badly written.
  191. It is neither a valid ``key = value`` line,
  192. nor a valid section marker line.
  193. """
  194. class ReloadError(IOError):
  195. """
  196. A 'reload' operation failed.
  197. This exception is a subclass of ``IOError``.
  198. """
  199. def __init__(self):
  200. IOError.__init__(self, 'reload failed, filename is not set.')
  201. class DuplicateError(ConfigObjError):
  202. """
  203. The keyword or section specified already exists.
  204. """
  205. class ConfigspecError(ConfigObjError):
  206. """
  207. An error occured whilst parsing a configspec.
  208. """
  209. class InterpolationError(ConfigObjError):
  210. """Base class for the two interpolation errors."""
  211. class InterpolationLoopError(InterpolationError):
  212. """Maximum interpolation depth exceeded in string interpolation."""
  213. def __init__(self, option):
  214. InterpolationError.__init__(
  215. self,
  216. 'interpolation loop detected in value "%s".' % option)
  217. class RepeatSectionError(ConfigObjError):
  218. """
  219. This error indicates additional sections in a section with a
  220. ``__many__`` (repeated) section.
  221. """
  222. class MissingInterpolationOption(InterpolationError):
  223. """A value specified for interpolation was missing."""
  224. def __init__(self, option):
  225. msg = 'missing option "%s" in interpolation.' % option
  226. InterpolationError.__init__(self, msg)
  227. class UnreprError(ConfigObjError):
  228. """An error parsing in unrepr mode."""
  229. class InterpolationEngine(object):
  230. """
  231. A helper class to help perform string interpolation.
  232. This class is an abstract base class; its descendants perform
  233. the actual work.
  234. """
  235. # compiled regexp to use in self.interpolate()
  236. _KEYCRE = re.compile(r"%\(([^)]*)\)s")
  237. _cookie = '%'
  238. def __init__(self, section):
  239. # the Section instance that "owns" this engine
  240. self.section = section
  241. def interpolate(self, key, value):
  242. # short-cut
  243. if not self._cookie in value:
  244. return value
  245. def recursive_interpolate(key, value, section, backtrail):
  246. """The function that does the actual work.
  247. ``value``: the string we're trying to interpolate.
  248. ``section``: the section in which that string was found
  249. ``backtrail``: a dict to keep track of where we've been,
  250. to detect and prevent infinite recursion loops
  251. This is similar to a depth-first-search algorithm.
  252. """
  253. # Have we been here already?
  254. if (key, section.name) in backtrail:
  255. # Yes - infinite loop detected
  256. raise InterpolationLoopError(key)
  257. # Place a marker on our backtrail so we won't come back here again
  258. backtrail[(key, section.name)] = 1
  259. # Now start the actual work
  260. match = self._KEYCRE.search(value)
  261. while match:
  262. # The actual parsing of the match is implementation-dependent,
  263. # so delegate to our helper function
  264. k, v, s = self._parse_match(match)
  265. if k is None:
  266. # That's the signal that no further interpolation is needed
  267. replacement = v
  268. else:
  269. # Further interpolation may be needed to obtain final value
  270. replacement = recursive_interpolate(k, v, s, backtrail)
  271. # Replace the matched string with its final value
  272. start, end = match.span()
  273. value = ''.join((value[:start], replacement, value[end:]))
  274. new_search_start = start + len(replacement)
  275. # Pick up the next interpolation key, if any, for next time
  276. # through the while loop
  277. match = self._KEYCRE.search(value, new_search_start)
  278. # Now safe to come back here again; remove marker from backtrail
  279. del backtrail[(key, section.name)]
  280. return value
  281. # Back in interpolate(), all we have to do is kick off the recursive
  282. # function with appropriate starting values
  283. value = recursive_interpolate(key, value, self.section, {})
  284. return value
  285. def _fetch(self, key):
  286. """Helper function to fetch values from owning section.
  287. Returns a 2-tuple: the value, and the section where it was found.
  288. """
  289. # switch off interpolation before we try and fetch anything !
  290. save_interp = self.section.main.interpolation
  291. self.section.main.interpolation = False
  292. # Start at section that "owns" this InterpolationEngine
  293. current_section = self.section
  294. while True:
  295. # try the current section first
  296. val = current_section.get(key)
  297. if val is not None and not isinstance(val, Section):
  298. break
  299. # try "DEFAULT" next
  300. val = current_section.get('DEFAULT', {}).get(key)
  301. if val is not None and not isinstance(val, Section):
  302. break
  303. # move up to parent and try again
  304. # top-level's parent is itself
  305. if current_section.parent is current_section:
  306. # reached top level, time to give up
  307. break
  308. current_section = current_section.parent
  309. # restore interpolation to previous value before returning
  310. self.section.main.interpolation = save_interp
  311. if val is None:
  312. raise MissingInterpolationOption(key)
  313. return val, current_section
  314. def _parse_match(self, match):
  315. """Implementation-dependent helper function.
  316. Will be passed a match object corresponding to the interpolation
  317. key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
  318. key in the appropriate config file section (using the ``_fetch()``
  319. helper function) and return a 3-tuple: (key, value, section)
  320. ``key`` is the name of the key we're looking for
  321. ``value`` is the value found for that key
  322. ``section`` is a reference to the section where it was found
  323. ``key`` and ``section`` should be None if no further
  324. interpolation should be performed on the resulting value
  325. (e.g., if we interpolated "$$" and returned "$").
  326. """
  327. raise NotImplementedError()
  328. class ConfigParserInterpolation(InterpolationEngine):
  329. """Behaves like ConfigParser."""
  330. _cookie = '%'
  331. _KEYCRE = re.compile(r"%\(([^)]*)\)s")
  332. def _parse_match(self, match):
  333. key = match.group(1)
  334. value, section = self._fetch(key)
  335. return key, value, section
  336. class TemplateInterpolation(InterpolationEngine):
  337. """Behaves like string.Template."""
  338. _cookie = '$'
  339. _delimiter = '$'
  340. _KEYCRE = re.compile(r"""
  341. \$(?:
  342. (?P<escaped>\$) | # Two $ signs
  343. (?P<named>[_a-z][_a-z0-9]*) | # $name format
  344. {(?P<braced>[^}]*)} # ${name} format
  345. )
  346. """, re.IGNORECASE | re.VERBOSE)
  347. def _parse_match(self, match):
  348. # Valid name (in or out of braces): fetch value from section
  349. key = match.group('named') or match.group('braced')
  350. if key is not None:
  351. value, section = self._fetch(key)
  352. return key, value, section
  353. # Escaped delimiter (e.g., $$): return single delimiter
  354. if match.group('escaped') is not None:
  355. # Return None for key and section to indicate it's time to stop
  356. return None, self._delimiter, None
  357. # Anything else: ignore completely, just return it unchanged
  358. return None, match.group(), None
  359. interpolation_engines = {
  360. 'configparser': ConfigParserInterpolation,
  361. 'template': TemplateInterpolation,
  362. }
  363. def __newobj__(cls, *args):
  364. # Hack for pickle
  365. return cls.__new__(cls, *args)
  366. class Section(dict):
  367. """
  368. A dictionary-like object that represents a section in a config file.
  369. It does string interpolation if the 'interpolation' attribute
  370. of the 'main' object is set to True.
  371. Interpolation is tried first from this object, then from the 'DEFAULT'
  372. section of this object, next from the parent and its 'DEFAULT' section,
  373. and so on until the main object is reached.
  374. A Section will behave like an ordered dictionary - following the
  375. order of the ``scalars`` and ``sections`` attributes.
  376. You can use this to change the order of members.
  377. Iteration follows the order: scalars, then sections.
  378. """
  379. def __setstate__(self, state):
  380. dict.update(self, state[0])
  381. self.__dict__.update(state[1])
  382. def __reduce__(self):
  383. state = (dict(self), self.__dict__)
  384. return (__newobj__, (self.__class__,), state)
  385. def __init__(self, parent, depth, main, indict=None, name=None):
  386. """
  387. * parent is the section above
  388. * depth is the depth level of this section
  389. * main is the main ConfigObj
  390. * indict is a dictionary to initialise the section with
  391. """
  392. if indict is None:
  393. indict = {}
  394. dict.__init__(self)
  395. # used for nesting level *and* interpolation
  396. self.parent = parent
  397. # used for the interpolation attribute
  398. self.main = main
  399. # level of nesting depth of this Section
  400. self.depth = depth
  401. # purely for information
  402. self.name = name
  403. #
  404. self._initialise()
  405. # we do this explicitly so that __setitem__ is used properly
  406. # (rather than just passing to ``dict.__init__``)
  407. for entry, value in indict.iteritems():
  408. self[entry] = value
  409. def _initialise(self):
  410. # the sequence of scalar values in this Section
  411. self.scalars = []
  412. # the sequence of sections in this Section
  413. self.sections = []
  414. # for comments :-)
  415. self.comments = {}
  416. self.inline_comments = {}
  417. # the configspec
  418. self.configspec = None
  419. # for defaults
  420. self.defaults = []
  421. self.default_values = {}
  422. self.extra_values = []
  423. self._created = False
  424. def _interpolate(self, key, value):
  425. try:
  426. # do we already have an interpolation engine?
  427. engine = self._interpolation_engine
  428. except AttributeError:
  429. # not yet: first time running _interpolate(), so pick the engine
  430. name = self.main.interpolation
  431. if name == True: # note that "if name:" would be incorrect here
  432. # backwards-compatibility: interpolation=True means use default
  433. name = DEFAULT_INTERPOLATION
  434. name = name.lower() # so that "Template", "template", etc. all work
  435. class_ = interpolation_engines.get(name, None)
  436. if class_ is None:
  437. # invalid value for self.main.interpolation
  438. self.main.interpolation = False
  439. return value
  440. else:
  441. # save reference to engine so we don't have to do this again
  442. engine = self._interpolation_engine = class_(self)
  443. # let the engine do the actual work
  444. return engine.interpolate(key, value)
  445. def __getitem__(self, key):
  446. """Fetch the item and do string interpolation."""
  447. val = dict.__getitem__(self, key)
  448. if self.main.interpolation:
  449. if isinstance(val, basestring):
  450. return self._interpolate(key, val)
  451. if isinstance(val, list):
  452. def _check(entry):
  453. if isinstance(entry, basestring):
  454. return self._interpolate(key, entry)
  455. return entry
  456. new = [_check(entry) for entry in val]
  457. if new != val:
  458. return new
  459. return val
  460. def __setitem__(self, key, value, unrepr=False):
  461. """
  462. Correctly set a value.
  463. Making dictionary values Section instances.
  464. (We have to special case 'Section' instances - which are also dicts)
  465. Keys must be strings.
  466. Values need only be strings (or lists of strings) if
  467. ``main.stringify`` is set.
  468. ``unrepr`` must be set when setting a value to a dictionary, without
  469. creating a new sub-section.
  470. """
  471. if not isinstance(key, basestring):
  472. raise ValueError('The key "%s" is not a string.' % key)
  473. # add the comment
  474. if key not in self.comments:
  475. self.comments[key] = []
  476. self.inline_comments[key] = ''
  477. # remove the entry from defaults
  478. if key in self.defaults:
  479. self.defaults.remove(key)
  480. #
  481. if isinstance(value, Section):
  482. if key not in self:
  483. self.sections.append(key)
  484. dict.__setitem__(self, key, value)
  485. elif isinstance(value, dict) and not unrepr:
  486. # First create the new depth level,
  487. # then create the section
  488. if key not in self:
  489. self.sections.append(key)
  490. new_depth = self.depth + 1
  491. dict.__setitem__(
  492. self,
  493. key,
  494. Section(
  495. self,
  496. new_depth,
  497. self.main,
  498. indict=value,
  499. name=key))
  500. else:
  501. if key not in self:
  502. self.scalars.append(key)
  503. if not self.main.stringify:
  504. if isinstance(value, basestring):
  505. pass
  506. elif isinstance(value, (list, tuple)):
  507. for entry in value:
  508. if not isinstance(entry, basestring):
  509. raise TypeError('Value is not a string "%s".' % entry)
  510. else:
  511. raise TypeError('Value is not a string "%s".' % value)
  512. dict.__setitem__(self, key, value)
  513. def __delitem__(self, key):
  514. """Remove items from the sequence when deleting."""
  515. dict. __delitem__(self, key)
  516. if key in self.scalars:
  517. self.scalars.remove(key)
  518. else:
  519. self.sections.remove(key)
  520. del self.comments[key]
  521. del self.inline_comments[key]
  522. def get(self, key, default=None):
  523. """A version of ``get`` that doesn't bypass string interpolation."""
  524. try:
  525. return self[key]
  526. except KeyError:
  527. return default
  528. def update(self, indict):
  529. """
  530. A version of update that uses our ``__setitem__``.
  531. """
  532. for entry in indict:
  533. self[entry] = indict[entry]
  534. def pop(self, key, default=MISSING):
  535. """
  536. 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  537. If key is not found, d is returned if given, otherwise KeyError is raised'
  538. """
  539. try:
  540. val = self[key]
  541. except KeyError:
  542. if default is MISSING:
  543. raise
  544. val = default
  545. else:
  546. del self[key]
  547. return val
  548. def popitem(self):
  549. """Pops the first (key,val)"""
  550. sequence = (self.scalars + self.sections)
  551. if not sequence:
  552. raise KeyError(": 'popitem(): dictionary is empty'")
  553. key = sequence[0]
  554. val = self[key]
  555. del self[key]
  556. return key, val
  557. def clear(self):
  558. """
  559. A version of clear that also affects scalars/sections
  560. Also clears comments and configspec.
  561. Leaves other attributes alone :
  562. depth/main/parent are not affected
  563. """
  564. dict.clear(self)
  565. self.scalars = []
  566. self.sections = []
  567. self.comments = {}
  568. self.inline_comments = {}
  569. self.configspec = None
  570. self.defaults = []
  571. self.extra_values = []
  572. def setdefault(self, key, default=None):
  573. """A version of setdefault that sets sequence if appropriate."""
  574. try:
  575. return self[key]
  576. except KeyError:
  577. self[key] = default
  578. return self[key]
  579. def items(self):
  580. """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
  581. return zip((self.scalars + self.sections), self.values())
  582. def keys(self):
  583. """D.keys() -> list of D's keys"""
  584. return (self.scalars + self.sections)
  585. def values(self):
  586. """D.values() -> list of D's values"""
  587. return [self[key] for key in (self.scalars + self.sections)]
  588. def iteritems(self):
  589. """D.iteritems() -> an iterator over the (key, value) items of D"""
  590. return iter(self.items())
  591. def iterkeys(self):
  592. """D.iterkeys() -> an iterator over the keys of D"""
  593. return iter((self.scalars + self.sections))
  594. __iter__ = iterkeys
  595. def itervalues(self):
  596. """D.itervalues() -> an iterator over the values of D"""
  597. return iter(self.values())
  598. def __repr__(self):
  599. """x.__repr__() <==> repr(x)"""
  600. def _getval(key):
  601. try:
  602. return self[key]
  603. except MissingInterpolationOption:
  604. return dict.__getitem__(self, key)
  605. return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(_getval(key))))
  606. for key in (self.scalars + self.sections)])
  607. __str__ = __repr__
  608. __str__.__doc__ = "x.__str__() <==> str(x)"
  609. # Extra methods - not in a normal dictionary
  610. def dict(self):
  611. """
  612. Return a deepcopy of self as a dictionary.
  613. All members that are ``Section`` instances are recursively turned to
  614. ordinary dictionaries - by calling their ``dict`` method.
  615. >>> n = a.dict()
  616. >>> n == a
  617. 1
  618. >>> n is a
  619. 0
  620. """
  621. newdict = {}
  622. for entry in self:
  623. this_entry = self[entry]
  624. if isinstance(this_entry, Section):
  625. this_entry = this_entry.dict()
  626. elif isinstance(this_entry, list):
  627. # create a copy rather than a reference
  628. this_entry = list(this_entry)
  629. elif isinstance(this_entry, tuple):
  630. # create a copy rather than a reference
  631. this_entry = tuple(this_entry)
  632. newdict[entry] = this_entry
  633. return newdict
  634. def merge(self, indict):
  635. """
  636. A recursive update - useful for merging config files.
  637. >>> a = '''[section1]
  638. ... option1 = True
  639. ... [[subsection]]
  640. ... more_options = False
  641. ... # end of file'''.splitlines()
  642. >>> b = '''# File is user.ini
  643. ... [section1]
  644. ... option1 = False
  645. ... # end of file'''.splitlines()
  646. >>> c1 = ConfigObj(b)
  647. >>> c2 = ConfigObj(a)
  648. >>> c2.merge(c1)
  649. >>> c2
  650. ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}})
  651. """
  652. for key, val in indict.items():
  653. if (key in self and isinstance(self[key], dict) and
  654. isinstance(val, dict)):
  655. self[key].merge(val)
  656. else:
  657. self[key] = val
  658. def rename(self, oldkey, newkey):
  659. """
  660. Change a keyname to another, without changing position in sequence.
  661. Implemented so that transformations can be made on keys,
  662. as well as on values. (used by encode and decode)
  663. Also renames comments.
  664. """
  665. if oldkey in self.scalars:
  666. the_list = self.scalars
  667. elif oldkey in self.sections:
  668. the_list = self.sections
  669. else:
  670. raise KeyError('Key "%s" not found.' % oldkey)
  671. pos = the_list.index(oldkey)
  672. #
  673. val = self[oldkey]
  674. dict.__delitem__(self, oldkey)
  675. dict.__setitem__(self, newkey, val)
  676. the_list.remove(oldkey)
  677. the_list.insert(pos, newkey)
  678. comm = self.comments[oldkey]
  679. inline_comment = self.inline_comments[oldkey]
  680. del self.comments[oldkey]
  681. del self.inline_comments[oldkey]
  682. self.comments[newkey] = comm
  683. self.inline_comments[newkey] = inline_comment
  684. def walk(self, function, raise_errors=True,
  685. call_on_sections=False, **keywargs):
  686. """
  687. Walk every member and call a function on the keyword and value.
  688. Return a dictionary of the return values
  689. If the function raises an exception, raise the errror
  690. unless ``raise_errors=False``, in which case set the return value to
  691. ``False``.
  692. Any unrecognised keyword arguments you pass to walk, will be pased on
  693. to the function you pass in.
  694. Note: if ``call_on_sections`` is ``True`` then - on encountering a
  695. subsection, *first* the function is called for the *whole* subsection,
  696. and then recurses into it's members. This means your function must be
  697. able to handle strings, dictionaries and lists. This allows you
  698. to change the key of subsections as well as for ordinary members. The
  699. return value when called on the whole subsection has to be discarded.
  700. See the encode and decode methods for examples, including functions.
  701. .. admonition:: caution
  702. You can use ``walk`` to transform the names of members of a section
  703. but you mustn't add or delete members.
  704. >>> config = '''[XXXXsection]
  705. ... XXXXkey = XXXXvalue'''.splitlines()
  706. >>> cfg = ConfigObj(config)
  707. >>> cfg
  708. ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}})
  709. >>> def transform(section, key):
  710. ... val = section[key]
  711. ... newkey = key.replace('XXXX', 'CLIENT1')
  712. ... section.rename(key, newkey)
  713. ... if isinstance(val, (tuple, list, dict)):
  714. ... pass
  715. ... else:
  716. ... val = val.replace('XXXX', 'CLIENT1')
  717. ... section[newkey] = val
  718. >>> cfg.walk(transform, call_on_sections=True)
  719. {'CLIENT1section': {'CLIENT1key': None}}
  720. >>> cfg
  721. ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
  722. """
  723. out = {}
  724. # scalars first
  725. for i in range(len(self.scalars)):
  726. entry = self.scalars[i]
  727. try:
  728. val = function(self, entry, **keywargs)
  729. # bound again in case name has changed
  730. entry = self.scalars[i]
  731. out[entry] = val
  732. except Exception:
  733. if raise_errors:
  734. raise
  735. else:
  736. entry = self.scalars[i]
  737. out[entry] = False
  738. # then sections
  739. for i in range(len(self.sections)):
  740. entry = self.sections[i]
  741. if call_on_sections:
  742. try:
  743. function(self, entry, **keywargs)
  744. except Exception:
  745. if raise_errors:
  746. raise
  747. else:
  748. entry = self.sections[i]
  749. out[entry] = False
  750. # bound again in case name has changed
  751. entry = self.sections[i]
  752. # previous result is discarded
  753. out[entry] = self[entry].walk(
  754. function,
  755. raise_errors=raise_errors,
  756. call_on_sections=call_on_sections,
  757. **keywargs)
  758. return out
  759. def as_bool(self, key):
  760. """
  761. Accepts a key as input. The corresponding value must be a string or
  762. the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
  763. retain compatibility with Python 2.2.
  764. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
  765. ``True``.
  766. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
  767. ``False``.
  768. ``as_bool`` is not case sensitive.
  769. Any other input will raise a ``ValueError``.
  770. >>> a = ConfigObj()
  771. >>> a['a'] = 'fish'
  772. >>> a.as_bool('a')
  773. Traceback (most recent call last):
  774. ValueError: Value "fish" is neither True nor False
  775. >>> a['b'] = 'True'
  776. >>> a.as_bool('b')
  777. 1
  778. >>> a['b'] = 'off'
  779. >>> a.as_bool('b')
  780. 0
  781. """
  782. val = self[key]
  783. if val == True:
  784. return True
  785. elif val == False:
  786. return False
  787. else:
  788. try:
  789. if not isinstance(val, basestring):
  790. # TODO: Why do we raise a KeyError here?
  791. raise KeyError()
  792. else:
  793. return self.main._bools[val.lower()]
  794. except KeyError:
  795. raise ValueError('Value "%s" is neither True nor False' % val)
  796. def as_int(self, key):
  797. """
  798. A convenience method which coerces the specified value to an integer.
  799. If the value is an invalid literal for ``int``, a ``ValueError`` will
  800. be raised.
  801. >>> a = ConfigObj()
  802. >>> a['a'] = 'fish'
  803. >>> a.as_int('a')
  804. Traceback (most recent call last):
  805. ValueError: invalid literal for int() with base 10: 'fish'
  806. >>> a['b'] = '1'
  807. >>> a.as_int('b')
  808. 1
  809. >>> a['b'] = '3.2'
  810. >>> a.as_int('b')
  811. Traceback (most recent call last):
  812. ValueError: invalid literal for int() with base 10: '3.2'
  813. """
  814. return int(self[key])
  815. def as_float(self, key):
  816. """
  817. A convenience method which coerces the specified value to a float.
  818. If the value is an invalid literal for ``float``, a ``ValueError`` will
  819. be raised.
  820. >>> a = ConfigObj()
  821. >>> a['a'] = 'fish'
  822. >>> a.as_float('a')
  823. Traceback (most recent call last):
  824. ValueError: invalid literal for float(): fish
  825. >>> a['b'] = '1'
  826. >>> a.as_float('b')
  827. 1.0
  828. >>> a['b'] = '3.2'
  829. >>> a.as_float('b')
  830. 3.2000000000000002
  831. """
  832. return float(self[key])
  833. def as_list(self, key):
  834. """
  835. A convenience method which fetches the specified value, guaranteeing
  836. that it is a list.
  837. >>> a = ConfigObj()
  838. >>> a['a'] = 1
  839. >>> a.as_list('a')
  840. [1]
  841. >>> a['a'] = (1,)
  842. >>> a.as_list('a')
  843. [1]
  844. >>> a['a'] = [1]
  845. >>> a.as_list('a')
  846. [1]
  847. """
  848. result = self[key]
  849. if isinstance(result, (tuple, list)):
  850. return list(result)
  851. return [result]
  852. def restore_default(self, key):
  853. """
  854. Restore (and return) default value for the specified key.
  855. This method will only work for a ConfigObj that was created
  856. with a configspec and has been validated.
  857. If there is no default value for this key, ``KeyError`` is raised.
  858. """
  859. default = self.default_values[key]
  860. dict.__setitem__(self, key, default)
  861. if key not in self.defaults:
  862. self.defaults.append(key)
  863. return default
  864. def restore_defaults(self):
  865. """
  866. Recursively restore default values to all members
  867. that have them.
  868. This method will only work for a ConfigObj that was created
  869. with a configspec and has been validated.
  870. It doesn't delete or modify entries without default values.
  871. """
  872. for key in self.default_values:
  873. self.restore_default(key)
  874. for section in self.sections:
  875. self[section].restore_defaults()
  876. class ConfigObj(Section):
  877. """An object to read, create, and write config files."""
  878. _keyword = re.compile(r'''^ # line start
  879. (\s*) # indentation
  880. ( # keyword
  881. (?:".*?")| # double quotes
  882. (?:'.*?')| # single quotes
  883. (?:[^'"=].*?) # no quotes
  884. )
  885. \s*=\s* # divider
  886. (.*) # value (including list values and comments)
  887. $ # line end
  888. ''',
  889. re.VERBOSE)
  890. _sectionmarker = re.compile(r'''^
  891. (\s*) # 1: indentation
  892. ((?:\[\s*)+) # 2: section marker open
  893. ( # 3: section name open
  894. (?:"\s*\S.*?\s*")| # at least one non-space with double quotes
  895. (?:'\s*\S.*?\s*')| # at least one non-space with single quotes
  896. (?:[^'"\s].*?) # at least one non-space unquoted
  897. ) # section name close
  898. ((?:\s*\])+) # 4: section marker close
  899. \s*(\#.*)? # 5: optional comment
  900. $''',
  901. re.VERBOSE)
  902. # this regexp pulls list values out as a single string
  903. # or single values and comments
  904. # FIXME: this regex adds a '' to the end of comma terminated lists
  905. # workaround in ``_handle_value``
  906. _valueexp = re.compile(r'''^
  907. (?:
  908. (?:
  909. (
  910. (?:
  911. (?:
  912. (?:".*?")| # double quotes
  913. (?:'.*?')| # single quotes
  914. (?:[^'",\#][^,\#]*?) # unquoted
  915. )
  916. \s*,\s* # comma
  917. )* # match all list items ending in a comma (if any)
  918. )
  919. (
  920. (?:".*?")| # double quotes
  921. (?:'.*?')| # single quotes
  922. (?:[^'",\#\s][^,]*?)| # unquoted
  923. (?:(?<!,)) # Empty value
  924. )? # last item in a list - or string value
  925. )|
  926. (,) # alternatively a single comma - empty list
  927. )
  928. \s*(\#.*)? # optional comment
  929. $''',
  930. re.VERBOSE)
  931. # use findall to get the members of a list value
  932. _listvalueexp = re.compile(r'''
  933. (
  934. (?:".*?")| # double quotes
  935. (?:'.*?')| # single quotes
  936. (?:[^'",\#]?.*?) # unquoted
  937. )
  938. \s*,\s* # comma
  939. ''',
  940. re.VERBOSE)
  941. # this regexp is used for the value
  942. # when lists are switched off
  943. _nolistvalue = re.compile(r'''^
  944. (
  945. (?:".*?")| # double quotes
  946. (?:'.*?')| # single quotes
  947. (?:[^'"\#].*?)| # unquoted
  948. (?:) # Empty value
  949. )
  950. \s*(\#.*)? # optional comment
  951. $''',
  952. re.VERBOSE)
  953. # regexes for finding triple quoted values on one line
  954. _single_line_single = re.compile(r"^'''(.*?)'''\s*(#.*)?$")
  955. _single_line_double = re.compile(r'^"""(.*?)"""\s*(#.*)?$')
  956. _multi_line_single = re.compile(r"^(.*?)'''\s*(#.*)?$")
  957. _multi_line_double = re.compile(r'^(.*?)"""\s*(#.*)?$')
  958. _triple_quote = {
  959. "'''": (_single_line_single, _multi_line_single),
  960. '"""': (_single_line_double, _multi_line_double),
  961. }
  962. # Used by the ``istrue`` Section method
  963. _bools = {
  964. 'yes': True, 'no': False,
  965. 'on': True, 'off': False,
  966. '1': True, '0': False,
  967. 'true': True, 'false': False,
  968. }
  969. def __init__(self, infile=None, options=None, configspec=None, encoding=None,
  970. interpolation=True, raise_errors=False, list_values=True,
  971. create_empty=False, file_error=False, stringify=True,
  972. indent_type=None, default_encoding=None, unrepr=False,
  973. write_empty_values=False, _inspec=False):
  974. """
  975. Parse a config file or create a config file object.
  976. ``ConfigObj(infile=None, configspec=None, encoding=None,
  977. interpolation=True, raise_errors=False, list_values=True,
  978. create_empty=False, file_error=False, stringify=True,
  979. indent_type=None, default_encoding=None, unrepr=False,
  980. write_empty_values=False, _inspec=False)``
  981. """
  982. self._inspec = _inspec
  983. # init the superclass
  984. Section.__init__(self, self, 0, self)
  985. infile = infile or []
  986. _options = {'configspec': configspec,
  987. 'encoding': encoding, 'interpolation': interpolation,
  988. 'raise_errors': raise_errors, 'list_values': list_values,
  989. 'create_empty': create_empty, 'file_error': file_error,
  990. 'stringify': stringify, 'indent_type': indent_type,
  991. 'default_encoding': default_encoding, 'unrepr': unrepr,
  992. 'write_empty_values': write_empty_values}
  993. if options is None:
  994. options = _options
  995. else:
  996. import warnings
  997. warnings.warn('Passing in an options dictionary to ConfigObj() is '
  998. 'deprecated. Use **options instead.',
  999. DeprecationWarning, stacklevel=2)
  1000. # TODO: check the values too.
  1001. for entry in options:
  1002. if entry not in OPTION_DEFAULTS:
  1003. raise TypeError('Unrecognised option "%s".' % entry)
  1004. for entry, value in OPTION_DEFAULTS.items():
  1005. if entry not in options:
  1006. options[entry] = value
  1007. keyword_value = _options[entry]
  1008. if value != keyword_value:
  1009. options[entry] = keyword_value
  1010. # XXXX this ignores an explicit list_values = True in combination
  1011. # with _inspec. The user should *never* do that anyway, but still...
  1012. if _inspec:
  1013. options['list_values'] = False
  1014. self._initialise(options)
  1015. configspec = options['configspec']
  1016. self._original_configspec = configspec
  1017. self._load(infile, configspec)
  1018. def _load(self, infile, configspec):
  1019. if isinstance(infile, basestring):
  1020. self.filename = infile
  1021. if os.path.isfile(infile):
  1022. h = open(infile, 'rb')
  1023. infile = h.read() or []
  1024. h.close()
  1025. elif self.file_error:
  1026. # raise an error if the file doesn't exist
  1027. raise IOError('Config file not found: "%s".' % self.filename)
  1028. else:
  1029. # file doesn't already exist
  1030. if self.create_empty:
  1031. # this is a good test that the filename specified
  1032. # isn't impossible - like on a non-existent device
  1033. h = open(infile, 'w')
  1034. h.write('')
  1035. h.close()
  1036. infile = []
  1037. elif isinstance(infile, (list, tuple)):
  1038. infile = list(infile)
  1039. elif isinstance(infile, dict):
  1040. # initialise self
  1041. # the Section class handles creating subsections
  1042. if isinstance(infile, ConfigObj):
  1043. # get a copy of our ConfigObj
  1044. def set_section(in_section, this_section):
  1045. for entry in in_section.scalars:
  1046. this_section[entry] = in_section[entry]
  1047. for section in in_section.sections:
  1048. this_section[section] = {}
  1049. set_section(in_section[section], this_section[section])
  1050. set_section(infile, self)
  1051. else:
  1052. for entry in infile:
  1053. self[entry] = infile[entry]
  1054. del self._errors
  1055. if configspec is not None:
  1056. self._handle_configspec(configspec)
  1057. else:
  1058. self.configspec = None
  1059. return
  1060. elif getattr(infile, 'read', MISSING) is not MISSING:
  1061. # This supports file like objects
  1062. infile = infile.read() or []
  1063. # needs splitting into lines - but needs doing *after* decoding
  1064. # in case it's not an 8 bit encoding
  1065. else:
  1066. raise TypeError('infile must be a filename, file like object, or list of lines.')
  1067. if infile:
  1068. # don't do it for the empty ConfigObj
  1069. infile = self._handle_bom(infile)
  1070. # infile is now *always* a list
  1071. #
  1072. # Set the newlines attribute (first line ending it finds)
  1073. # and strip trailing '\n' or '\r' from lines
  1074. for line in infile:
  1075. if (not line) or (line[-1] not in ('\r', '\n', '\r\n')):
  1076. continue
  1077. for end in ('\r\n', '\n', '\r'):
  1078. if line.endswith(end):
  1079. self.newlines = end
  1080. break
  1081. break
  1082. infile = [line.rstrip('\r\n') for line in infile]
  1083. self._parse(infile)
  1084. # if we had any errors, now is the time to raise them
  1085. if self._errors:
  1086. info = "at line %s." % self._errors[0].line_number
  1087. if len(self._errors) > 1:
  1088. msg = "Parsing failed with several errors.\nFirst error %s" % info
  1089. error = ConfigObjError(msg)
  1090. else:
  1091. error = self._errors[0]
  1092. # set the errors attribute; it's a list of tuples:
  1093. # (error_type, message, line_number)
  1094. error.errors = self._errors
  1095. # set the config attribute
  1096. error.config = self
  1097. raise error
  1098. # delete private attributes
  1099. del self._errors
  1100. if configspec is None:
  1101. self.configspec = None
  1102. else:
  1103. self._handle_configspec(configspec)
  1104. def _initialise(self, options=None):
  1105. if options is None:
  1106. options = OPTION_DEFAULTS
  1107. # initialise a few variables
  1108. self.filename = None
  1109. self._errors = []
  1110. self.raise_errors = options['raise_errors']
  1111. self.interpolation = options['interpolation']
  1112. self.list_values = options['list_values']
  1113. self.create_empty = options['create_empty']
  1114. self.file_error = options['file_error']
  1115. self.stringify = options['stringify']
  1116. self.indent_type = options['indent_type']
  1117. self.encoding = options['encoding']
  1118. self.default_encoding = options['default_encoding']
  1119. self.BOM = False
  1120. self.newlines = None
  1121. self.write_empty_values = options['write_empty_values']
  1122. self.unrepr = options['unrepr']
  1123. self.initial_comment = []
  1124. self.final_comment = []
  1125. self.configspec = None
  1126. if self._inspec:
  1127. self.list_values = False
  1128. # Clear section attributes as well
  1129. Section._initialise(self)
  1130. def __repr__(self):
  1131. def _getval(key):
  1132. try:
  1133. return self[key]
  1134. except MissingInterpolationOption:
  1135. return dict.__getitem__(self, key)
  1136. return ('ConfigObj({%s})' %
  1137. ', '.join([('%s: %s' % (repr(key), repr(_getval(key))))
  1138. for key in (self.scalars + self.sections)]))
  1139. def _handle_bom(self, infile):
  1140. """
  1141. Handle any BOM, and decode if necessary.
  1142. If an encoding is specified, that *must* be used - but the BOM should
  1143. still be removed (and the BOM attribute set).
  1144. (If the encoding is wrongly specified, then a BOM for an alternative
  1145. encoding won't be discovered or removed.)
  1146. If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
  1147. removed. The BOM attribute will be set. UTF16 will be decoded to
  1148. unicode.
  1149. NOTE: This method must not be called with an empty ``infile``.
  1150. Specifying the *wrong* encoding is likely to cause a
  1151. ``UnicodeDecodeError``.
  1152. ``infile`` must always be returned as a list of lines, but may be
  1153. passed in as a single string.
  1154. """
  1155. if ((self.encoding is not None) and
  1156. (self.encoding.lower() not in BOM_LIST)):
  1157. # No need to check for a BOM
  1158. # the encoding specified doesn't have one
  1159. # just decode
  1160. return self._decode(infile, self.encoding)
  1161. if isinstance(infile, (list, tuple)):
  1162. line = infile[0]
  1163. else:
  1164. line = infile
  1165. if self.encoding is not None:
  1166. # encoding explicitly supplied
  1167. # And it could have an associated BOM
  1168. # TODO: if encoding is just UTF16 - we ought to check for both
  1169. # TODO: big endian and little endian versions.
  1170. enc = BOM_LIST[self.encoding.lower()]
  1171. if enc == 'utf_16':
  1172. # For UTF16 we try big endian and little endian
  1173. for BOM, (encoding, final_encoding) in BOMS.items():
  1174. if not final_encoding:
  1175. # skip UTF8
  1176. continue
  1177. if infile.startswith(BOM):
  1178. ### BOM discovered
  1179. ##self.BOM = True
  1180. # Don't need to remove BOM
  1181. return self._decode(infile, encoding)
  1182. # If we get this far, will *probably* raise a DecodeError
  1183. # As it doesn't appear to start with a BOM
  1184. return self._decode(infile, self.encoding)
  1185. # Must be UTF8
  1186. BOM = BOM_SET[enc]
  1187. if not line.startswith(BOM):
  1188. return self._decode(infile, self.encoding)
  1189. newline = line[len(BOM):]
  1190. # BOM removed
  1191. if isinstance(infile, (list, tuple)):
  1192. infile[0] = newline
  1193. else:
  1194. infile = newline
  1195. self.BOM = True
  1196. return self._decode(infile, self.encoding)
  1197. # No encoding specified - so we need to check for UTF8/UTF16
  1198. for BOM, (encoding, final_encoding) in BOMS.items():
  1199. if not line.startswith(BOM):
  1200. continue
  1201. else:
  1202. # BOM discovered
  1203. self.encoding = final_encoding
  1204. if not final_encoding:
  1205. self.BOM = True
  1206. # UTF8
  1207. # remove BOM
  1208. newline = line[len(BOM):]
  1209. if isinstance(infile, (list, tuple)):
  1210. infile[0] = newline
  1211. else:
  1212. infile = newline
  1213. # UTF8 - don't decode
  1214. if isinstance(infile, basestring):
  1215. return infile.splitlines(True)
  1216. else:
  1217. return infile
  1218. # UTF16 - have to decode
  1219. return self._decode(infile, encoding)
  1220. # No BOM discovered and no encoding specified, just return
  1221. if isinstance(infile, basestring):
  1222. # infile read from a file will be a single string
  1223. return infile.splitlines(True)
  1224. return infile
  1225. def _a_to_u(self, aString):
  1226. """Decode ASCII strings to unicode if a self.encoding is specified."""
  1227. if self.encoding:
  1228. return aString.decode('ascii')
  1229. else:
  1230. return aString
  1231. def _decode(self, infile, encoding):
  1232. """
  1233. Decode infile to unicode. Using the specified encoding.
  1234. if is a string, it also needs converting to a list.
  1235. """
  1236. if isinstance(infile, basestring):
  1237. # can't be unicode
  1238. # NOTE: Could raise a ``UnicodeDecodeError``
  1239. return infile.decode(encoding).splitlines(True)
  1240. for i, line in enumerate(infile):
  1241. if not isinstance(line, unicode):
  1242. # NOTE: The isinstance test here handles mixed lists of unicode/string
  1243. # NOTE: But the decode will break on any non-string values
  1244. # NOTE: Or could raise a ``UnicodeDecodeError``
  1245. infile[i] = line.decode(encoding)
  1246. return infile
  1247. def _decode_element(self, line):
  1248. """Decode element to unicode if necessary."""
  1249. if not self.encoding:
  1250. return line
  1251. if isinstance(line, str) and self.default_encoding:
  1252. return line.decode(self.default_encoding)
  1253. return line
  1254. def _str(self, value):
  1255. """
  1256. Used by ``stringify`` within validate, to turn non-string values
  1257. into strings.
  1258. """
  1259. if not isinstance(value, basestring):
  1260. return str(value)
  1261. else:
  1262. return value
  1263. def _parse(self, infile):
  1264. """Actually parse the config file."""
  1265. temp_list_values = self.list_values
  1266. if self.unrepr:
  1267. self.list_values = False
  1268. comment_list = []
  1269. done_start = False
  1270. this_section = self
  1271. maxline = len(infile) - 1
  1272. cur_index = -1
  1273. reset_comment = False
  1274. while cur_index < maxline:
  1275. if reset_comment:
  1276. comment_list = []
  1277. cur_index += 1
  1278. line = infile[cur_index]
  1279. sline = line.strip()
  1280. # do we have anything on the line ?
  1281. if not sline or sline.startswith('#'):
  1282. reset_comment = False
  1283. comment_list.append(line)
  1284. continue
  1285. if not done_start:
  1286. # preserve initial comment
  1287. self.initial_comment = comment_list
  1288. comment_list = []
  1289. done_start = True
  1290. reset_comment = True
  1291. # first we check if it's a section marker
  1292. mat = self._sectionmarker.match(line)
  1293. if mat is not None:
  1294. # is a section line
  1295. (indent, sect_open, sect_name, sect_close, comment) = mat.groups()
  1296. if indent and (self.indent_type is None):
  1297. self.indent_type = indent
  1298. cur_depth = sect_open.count('[')
  1299. if cur_depth != sect_close.count(']'):
  1300. self._handle_error("Cannot compute the section depth at line %s.",
  1301. NestingError, infile, cur_index)
  1302. continue
  1303. if cur_depth < this_section.depth:
  1304. # the new section is dropping back to a previous level
  1305. try:
  1306. parent = self._match_depth(this_section,
  1307. cur_depth).parent
  1308. except SyntaxError:
  1309. self._handle_error("Cannot compute nesting level at line %s.",
  1310. NestingError, infile, cur_index)
  1311. continue
  1312. elif cur_depth == this_section.depth:
  1313. # the new section is a sibling of the current section
  1314. parent = this_section.parent
  1315. elif cur_depth == this_section.depth + 1:
  1316. # the new section is a child the current section
  1317. parent = this_section
  1318. else:
  1319. self._handle_error("Section too nested at line %s.",
  1320. NestingError, infile, cur_index)
  1321. sect_name = self._unquote(sect_name)
  1322. if sect_name in parent:
  1323. self._handle_error('Duplicate section name at line %s.',
  1324. DuplicateError, infile, cur_index)
  1325. continue
  1326. # create the new section
  1327. this_section = Section(
  1328. parent,
  1329. cur_depth,
  1330. self,
  1331. name=sect_name)
  1332. parent[sect_name] = this_section
  1333. parent.inline_comments[sect_name] = comment
  1334. parent.comments[sect_name] = comment_list
  1335. continue
  1336. #
  1337. # it's not a section marker,
  1338. # so it should be a valid ``key = value`` line
  1339. mat = self._keyword.match(line)
  1340. if mat is None:
  1341. # it neither matched as a keyword
  1342. # or a section marker
  1343. self._handle_error(
  1344. 'Invalid line at line "%s".',
  1345. ParseError, infile, cur_index)
  1346. else:
  1347. # is a keyword value
  1348. # value will include any inline comment
  1349. (indent, key, value) = mat.groups()
  1350. if indent and (self.indent_type is None):
  1351. self.indent_type = indent
  1352. # check for a multiline value
  1353. if value[:3] in ['"""', "'''"]:
  1354. try:
  1355. value, comment, cur_index = self._multiline(
  1356. value, infile, cur_index, maxline)
  1357. except SyntaxError:
  1358. self._handle_error(
  1359. 'Parse error in value at line %s.',
  1360. ParseError, infile, cur_index)
  1361. continue
  1362. else:
  1363. if self.unrepr:
  1364. comment = ''
  1365. try:
  1366. value = unrepr(value)
  1367. except Exception, e:
  1368. if type(e) == UnknownType:
  1369. msg = 'Unknown name or type in value at line %s.'
  1370. else:
  1371. msg = 'Parse error in value at line %s.'
  1372. self._handle_error(msg, UnreprError, infile,
  1373. cur_index)
  1374. continue
  1375. else:
  1376. if self.unrepr:
  1377. comment = ''
  1378. try:
  1379. value = unrepr(value)
  1380. except Exception, e:
  1381. if isinstance(e, UnknownType):
  1382. msg = 'Unknown name or type in value at line %s.'
  1383. else:
  1384. msg = 'Parse error in value at line %s.'
  1385. self._handle_error(msg, UnreprError, infile,
  1386. cur_index)
  1387. continue
  1388. else:
  1389. # extract comment and lists
  1390. try:
  1391. (value, comment) = self._handle_value(value)
  1392. except SyntaxError:
  1393. self._handle_error(
  1394. 'Parse error in value at line %s.',
  1395. ParseError, infile, cur_index)
  1396. continue
  1397. #
  1398. key = self._unquote(key)
  1399. if key in this_section:
  1400. self._handle_error(
  1401. 'Duplicate keyword name at line %s.',
  1402. DuplicateError, infile, cur_index)
  1403. continue
  1404. # add the key.
  1405. # we set unrepr because if we have got this far we will never
  1406. # be creating a new section
  1407. this_section.__setitem__(key, value, unrepr=True)
  1408. this_section.inline_comments[key] = comment
  1409. this_section.comments[key] = comment_list
  1410. continue
  1411. #
  1412. if self.indent_type is None:
  1413. # no indentation used, set the type accordingly
  1414. self.indent_type = ''
  1415. # preserve the final comment
  1416. if not self and not self.initial_comment:
  1417. self.initial_comment = comment_list
  1418. elif not reset_comment:
  1419. self.final_comment = comment_list
  1420. self.list_values = temp_list_values
  1421. def _match_depth(self, sect, depth):
  1422. """
  1423. Given a section and a depth level, walk back through the sections
  1424. parents to see if the depth level matches a previous section.
  1425. Return a reference to the right section,
  1426. or raise a SyntaxError.
  1427. """
  1428. while depth < sect.depth:
  1429. if sect is sect.parent:
  1430. # we've reached the top level already
  1431. raise SyntaxError()
  1432. sect = sect.parent
  1433. if sect.depth == depth:
  1434. return sect
  1435. # shouldn't get here
  1436. raise SyntaxError()
  1437. def _handle_error(self, text, ErrorClass, infile, cur_index):
  1438. """
  1439. Handle an error according to the error settings.
  1440. Either raise the error or store it.
  1441. The error will have occured at ``cur_index``
  1442. """
  1443. line = infile[cur_index]
  1444. cur_index += 1
  1445. message = text % cur_index
  1446. error = ErrorClass(message, cur_index, line)
  1447. if self.raise_errors:
  1448. # raise the error - parsing stops here
  1449. raise error
  1450. # store the error
  1451. # reraise when parsing has finished
  1452. self._errors.append(error)
  1453. def _unquote(self, value):
  1454. """Return an unquoted version of a value"""
  1455. if not value:
  1456. # should only happen during parsing of lists
  1457. raise SyntaxError
  1458. if (value[0] == value[-1]) and (value[0] in ('"', "'")):
  1459. value = value[1:-1]
  1460. return value
  1461. def _quote(self, value, multiline=True):
  1462. """
  1463. Return a safely quoted version of a value.
  1464. Raise a ConfigObjError if the value cannot be safely quoted.
  1465. If multiline is ``True`` (default) then use triple quotes
  1466. if necessary.
  1467. * Don't quote values that don't need it.
  1468. * Recursively quote members of a list and return a comma joined list.
  1469. * Multiline is ``False`` for lists.
  1470. * Obey list syntax for empty and single member lists.
  1471. If ``list_values=False`` then the value is only quoted if it contains
  1472. a ``\\n`` (is multiline) or '#'.
  1473. If ``write_empty_values`` is set, and the value is an empty string, it
  1474. won't be quoted.
  1475. """
  1476. if multiline and self.write_empty_values and value == '':
  1477. # Only if multiline is set, so that it is used for values not
  1478. # keys, and not values that are part of a list
  1479. return ''
  1480. if multiline and isinstance(value, (list, tuple)):
  1481. if not value:
  1482. return ','
  1483. elif len(value) == 1:
  1484. return self._quote(value[0], multiline=False) + ','
  1485. return ', '.join([self._quote(val, multiline=False)
  1486. for val in value])
  1487. if not isinstance(value, basestring):
  1488. if self.stringify:
  1489. value = str(value)
  1490. else:
  1491. raise TypeError('Value "%s" is not a string.' % value)
  1492. if not value:
  1493. return '""'
  1494. no_lists_no_quotes = not self.list_values and '\n' not in value and '#' not in value
  1495. need_triple = multiline and ((("'" in value) and ('"' in value)) or ('\n' in value ))
  1496. hash_triple_quote = multiline and not need_triple and ("'" in value) and ('"' in value) and ('#' in value)
  1497. check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote
  1498. if check_for_single:
  1499. if not self.list_values:
  1500. # we don't quote if ``list_values=False``
  1501. quot = noquot
  1502. # for normal values either single or double quotes will do
  1503. elif '\n' in value:
  1504. # will only happen if multiline is off - e.g. '\n' in key
  1505. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1506. elif ((value[0] not in wspace_plus) and
  1507. (value[-1] not in wspace_plus) and
  1508. (',' not in value)):
  1509. quot = noquot
  1510. else:
  1511. quot = self._get_single_quote(value)
  1512. else:
  1513. # if value has '\n' or "'" *and* '"', it will need triple quotes
  1514. quot = self._get_triple_quote(value)
  1515. if quot == noquot and '#' in value and self.list_values:
  1516. quot = self._get_single_quote(value)
  1517. return quot % value
  1518. def _get_single_quote(self, value):
  1519. if ("'" in value) and ('"' in value):
  1520. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1521. elif '"' in value:
  1522. quot = squot
  1523. else:
  1524. quot = dquot
  1525. return quot
  1526. def _get_triple_quote(self, value):
  1527. if (value.find('"""') != -1) and (value.find("'''") != -1):
  1528. raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1529. if value.find('"""') == -1:
  1530. quot = tdquot
  1531. else:
  1532. quot = tsquot
  1533. return quot
  1534. def _handle_value(self, value):
  1535. """
  1536. Given a value string, unquote, remove comment,
  1537. handle lists. (including empty and single member lists)
  1538. """
  1539. if self._inspec:
  1540. # Parsing a configspec so don't handle comments
  1541. return (value, '')
  1542. # do we look for lists in values ?
  1543. if not self.list_values:
  1544. mat = self._nolistvalue.match(value)
  1545. if mat is None:
  1546. raise SyntaxError()
  1547. # NOTE: we don't unquote here
  1548. return mat.groups()
  1549. #
  1550. mat = self._valueexp.match(value)
  1551. if mat is None:
  1552. # the value is badly constructed, probably badly quoted,
  1553. # or an invalid list
  1554. raise SyntaxError()
  1555. (list_values, single, empty_list, comment) = mat.groups()
  1556. if (list_values == '') and (single is None):
  1557. # change this if you want to accept empty values
  1558. raise SyntaxError()
  1559. # NOTE: note there is no error handling from here if the regex
  1560. # is wrong: then incorrect values will slip through
  1561. if empty_list is not None:
  1562. # the single comma - meaning an empty list
  1563. return ([], comment)
  1564. if single is not None:
  1565. # handle empty values
  1566. if list_values and not single:
  1567. # FIXME: the '' is a workaround because our regex now matches
  1568. # '' at the end of a list if it has a trailing comma
  1569. single = None
  1570. else:
  1571. single = single or '""'
  1572. single = self._unquote(single)
  1573. if list_values == '':
  1574. # not a list value
  1575. return (single, comment)
  1576. the_list = self._listvalueexp.findall(list_values)
  1577. the_list = [self._unquote(val) for val in the_list]
  1578. if single is not None:
  1579. the_list += [single]
  1580. return (the_list, comment)
  1581. def _multiline(self, value, infile, cur_index, maxline):
  1582. """Extract the value, where we are in a multiline situation."""
  1583. quot = value[:3]
  1584. newvalue = value[3:]
  1585. single_line = self._triple_quote[quot][0]
  1586. multi_line = self._triple_quote[quot][1]
  1587. mat = single_line.match(value)
  1588. if mat is not None:
  1589. retval = list(mat.groups())
  1590. retval.append(cur_index)
  1591. return retval
  1592. elif newvalue.find(quot) != -1:
  1593. # somehow the triple quote is missing
  1594. raise SyntaxError()
  1595. #
  1596. while cur_index < maxline:
  1597. cur_index += 1
  1598. newvalue += '\n'
  1599. line = infile[cur_index]
  1600. if line.find(quot) == -1:
  1601. newvalue += line
  1602. else:
  1603. # end of multiline, process it
  1604. break
  1605. else:
  1606. # we've got to the end of the config, oops...
  1607. raise SyntaxError()
  1608. mat = multi_line.match(line)
  1609. if mat is None:
  1610. # a badly formed line
  1611. raise SyntaxError()
  1612. (value, comment) = mat.groups()
  1613. return (newvalue + value, comment, cur_index)
  1614. def _handle_configspec(self, configspec):
  1615. """Parse the configspec."""
  1616. # FIXME: Should we check that the configspec was created with the
  1617. # correct settings ? (i.e. ``list_values=False``)
  1618. if not isinstance(configspec, ConfigObj):
  1619. try:
  1620. configspec = ConfigObj(configspec,
  1621. raise_errors=True,
  1622. file_error=True,
  1623. _inspec=True)
  1624. except ConfigObjError, e:
  1625. # FIXME: Should these errors have a reference
  1626. # to the already parsed ConfigObj ?
  1627. raise ConfigspecError('Parsing configspec failed: %s' % e)
  1628. except IOError, e:
  1629. raise IOError('Reading configspec failed: %s' % e)
  1630. self.configspec = configspec
  1631. def _set_configspec(self, section, copy):
  1632. """
  1633. Called by validate. Handles setting the configspec on subsections
  1634. including sections to be validated by __many__
  1635. """
  1636. configspec = section.configspec
  1637. many = configspec.get('__many__')
  1638. if isinstance(many, dict):
  1639. for entry in section.sections:
  1640. if entry not in configspec:
  1641. section[entry].configspec = many
  1642. for entry in configspec.sections:
  1643. if entry == '__many__':
  1644. continue
  1645. if entry not in section:
  1646. section[entry] = {}
  1647. section[entry]._created = True
  1648. if copy:
  1649. # copy comments
  1650. section.comments[entry] = configspec.comments.get(entry, [])
  1651. section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
  1652. # Could be a scalar when we expect a section
  1653. if isinstance(section[entry], Section):
  1654. section[entry].configspec = configspec[entry]
  1655. def _write_line(self, indent_string, entry, this_entry, comment):
  1656. """Write an individual line, for the write method"""
  1657. # NOTE: the calls to self._quote here handles non-StringType values.
  1658. if not self.unrepr:
  1659. val = self._decode_element(self._quote(this_entry))
  1660. else:
  1661. val = repr(this_entry)
  1662. return '%s%s%s%s%s' % (indent_string,
  1663. self._decode_element(self._quote(entry, multiline=False)),
  1664. self._a_to_u(' = '),
  1665. val,
  1666. self._decode_element(comment))
  1667. def _write_marker(self, indent_string, depth, entry, comment):
  1668. """Write a section marker line"""
  1669. return '%s%s%s%s%s' % (indent_string,
  1670. self._a_to_u('[' * depth),
  1671. self._quote(self._decode_element(entry), multiline=False),
  1672. self._a_to_u(']' * depth),
  1673. self._decode_element(comment))
  1674. def _handle_comment(self, comment):
  1675. """Deal with a comment."""
  1676. if not comment:
  1677. return ''
  1678. start = self.indent_type
  1679. if not comment.startswith('#'):
  1680. start += self._a_to_u(' # ')
  1681. return (start + comment)
  1682. # Public methods
  1683. def write(self, outfile=None, section=None):
  1684. """
  1685. Write the current ConfigObj as a file
  1686. tekNico: FIXME: use StringIO instead of real files
  1687. >>> filename = a.filename
  1688. >>> a.filename = 'test.ini'
  1689. >>> a.write()
  1690. >>> a.filename = filename
  1691. >>> a == ConfigObj('test.ini', raise_errors=True)
  1692. 1
  1693. >>> import os
  1694. >>> os.remove('test.ini')
  1695. """
  1696. if self.indent_type is None:
  1697. # this can be true if initialised from a dictionary
  1698. self.indent_type = DEFAULT_INDENT_TYPE
  1699. out = []
  1700. cs = self._a_to_u('#')
  1701. csp = self._a_to_u('# ')
  1702. if section is None:
  1703. int_val = self.interpolation
  1704. self.interpolation = False
  1705. section = self
  1706. for line in self.initial_comment:
  1707. line = self._decode_element(line)
  1708. stripped_line = line.strip()
  1709. if stripped_line and not stripped_line.startswith(cs):
  1710. line = csp + line
  1711. out.append(line)
  1712. indent_string = self.indent_type * section.depth
  1713. for entry in (section.scalars + section.sections):
  1714. if entry in section.defaults:
  1715. # don't write out default values
  1716. continue
  1717. for comment_line in section.comments[entry]:
  1718. comment_line = self._decode_element(comment_line.lstrip())
  1719. if comment_line and not comment_line.startswith(cs):
  1720. comment_line = csp + comment_line
  1721. out.append(indent_string + comment_line)
  1722. this_entry = section[entry]
  1723. comment = self._handle_comment(section.inline_comments[entry])
  1724. if isinstance(this_entry, dict):
  1725. # a section
  1726. out.append(self._write_marker(
  1727. indent_string,
  1728. this_entry.depth,
  1729. entry,
  1730. comment))
  1731. out.extend(self.write(section=this_entry))
  1732. else:
  1733. out.append(self._write_line(
  1734. indent_string,
  1735. entry,
  1736. this_entry,
  1737. comment))
  1738. if section is self:
  1739. for line in self.final_comment:
  1740. line = self._decode_element(line)
  1741. stripped_line = line.strip()
  1742. if stripped_line and not stripped_line.startswith(cs):
  1743. line = csp + line
  1744. out.append(line)
  1745. self.interpolation = int_val
  1746. if section is not self:
  1747. return out
  1748. if (self.filename is None) and (outfile is None):
  1749. # output a list of lines
  1750. # might need to encode
  1751. # NOTE: This will *screw* UTF16, each line will start with the BOM
  1752. if self.encoding:
  1753. out = [l.encode(self.encoding) for l in out]
  1754. if (self.BOM and ((self.encoding is None) or
  1755. (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))):
  1756. # Add the UTF8 BOM
  1757. if not out:
  1758. out.append('')
  1759. out[0] = BOM_UTF8 + out[0]
  1760. return out
  1761. # Turn the list to a string, joined with correct newlines
  1762. newline = self.newlines or os.linesep
  1763. if (getattr(outfile, 'mode', None) is not None and outfile.mode == 'w'
  1764. and sys.platform == 'win32' and newline == '\r\n'):
  1765. # Windows specific hack to avoid writing '\r\r\n'
  1766. newline = '\n'
  1767. output = self._a_to_u(newline).join(out)
  1768. if self.encoding:
  1769. output = output.encode(self.encoding)
  1770. if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)):
  1771. # Add the UTF8 BOM
  1772. output = BOM_UTF8 + output
  1773. if not output.endswith(newline):
  1774. output += newline
  1775. if outfile is not None:
  1776. outfile.write(output)
  1777. else:
  1778. h = open(self.filename, 'wb')
  1779. h.write(output)
  1780. h.close()
  1781. def validate(self, validator, preserve_errors=False, copy=False,
  1782. section=None):
  1783. """
  1784. Test the ConfigObj against a configspec.
  1785. It uses the ``validator`` object from *validate.py*.
  1786. To run ``validate`` on the current ConfigObj, call: ::
  1787. test = config.validate(validator)
  1788. (Normally having previously passed in the configspec when the ConfigObj
  1789. was created - you can dynamically assign a dictionary of checks to the
  1790. ``configspec`` attribute of a section though).
  1791. It returns ``True`` if everything passes, or a dictionary of
  1792. pass/fails (True/False). If every member of a subsection passes, it
  1793. will just have the value ``True``. (It also returns ``False`` if all
  1794. members fail).
  1795. In addition, it converts the values from strings to their native
  1796. types if their checks pass (and ``stringify`` is set).
  1797. If ``preserve_errors`` is ``True`` (``False`` is default) then instead
  1798. of a marking a fail with a ``False``, it will preserve the actual
  1799. exception object. This can contain info about the reason for failure.
  1800. For example the ``VdtValueTooSmallError`` indicates that the value
  1801. supplied was too small. If a value (or section) is missing it will
  1802. still be marked as ``False``.
  1803. You must have the validate module to use ``preserve_errors=True``.
  1804. You can then use the ``flatten_errors`` function to turn your nested
  1805. results dictionary into a flattened list of failures - useful for
  1806. displaying meaningful error messages.
  1807. """
  1808. if section is None:
  1809. if self.configspec is None:
  1810. raise ValueError('No configspec supplied.')
  1811. if preserve_errors:
  1812. # We do this once to remove a top level dependency on the validate module
  1813. # Which makes importing configobj faster
  1814. from validate import VdtMissingValue
  1815. self._vdtMissingValue = VdtMissingValue
  1816. section = self
  1817. if copy:
  1818. section.initial_comment = section.configspec.initial_comment
  1819. section.final_comment = section.configspec.final_comment
  1820. section.encoding = section.configspec.encoding
  1821. section.BOM = section.configspec.BOM
  1822. section.newlines = section.configspec.newlines
  1823. section.indent_type = section.configspec.indent_type
  1824. #
  1825. # section.default_values.clear() #??
  1826. configspec = section.configspec
  1827. self._set_configspec(section, copy)
  1828. def validate_entry(entry, spec, val, missing, ret_true, ret_false):
  1829. section.default_values.pop(entry, None)
  1830. try:
  1831. section.default_values[entry] = validator.get_default_value(configspec[entry])
  1832. except (KeyError, AttributeError, validator.baseErrorClass):
  1833. # No default, bad default or validator has no 'get_default_value'
  1834. # (e.g. SimpleVal)
  1835. pass
  1836. try:
  1837. check = validator.check(spec,
  1838. val,
  1839. missing=missing
  1840. )
  1841. except validator.baseErrorClass, e:
  1842. if not preserve_errors or isinstance(e, self._vdtMissingValue):
  1843. out[entry] = False
  1844. else:
  1845. # preserve the error
  1846. out[entry] = e
  1847. ret_false = False
  1848. ret_true = False
  1849. else:
  1850. ret_false = False
  1851. out[entry] = True
  1852. if self.stringify or missing:
  1853. # if we are doing type conversion
  1854. # or the value is a supplied default
  1855. if not self.stringify:
  1856. if isinstance(check, (list, tuple)):
  1857. # preserve lists
  1858. check = [self._str(item) for item in check]
  1859. elif missing and check is None:
  1860. # convert the None from a default to a ''
  1861. check = ''
  1862. else:
  1863. check = self._str(check)
  1864. if (check != val) or missing:
  1865. section[entry] = check
  1866. if not copy and missing and entry not in section.defaults:
  1867. section.defaults.append(entry)
  1868. return ret_true, ret_false
  1869. #
  1870. out = {}
  1871. ret_true = True
  1872. ret_false = True
  1873. unvalidated = [k for k in section.scalars if k not in configspec]
  1874. incorrect_sections = [k for k in configspec.sections if k in section.scalars]
  1875. incorrect_scalars = [k for k in configspec.scalars if k in section.sections]
  1876. for entry in configspec.scalars:
  1877. if entry in ('__many__', '___many___'):
  1878. # reserved names
  1879. continue
  1880. if (not entry in section.scalars) or (entry in section.defaults):
  1881. # missing entries
  1882. # or entries from defaults
  1883. missing = True
  1884. val = None
  1885. if copy and entry not in section.scalars:
  1886. # copy comments
  1887. section.comments[entry] = (
  1888. configspec.comments.get(entry, []))
  1889. section.inline_comments[entry] = (
  1890. configspec.inline_comments.get(entry, ''))
  1891. #
  1892. else:
  1893. missing = False
  1894. val = section[entry]
  1895. ret_true, ret_false = validate_entry(entry, configspec[entry], val,
  1896. missing, ret_true, ret_false)
  1897. many = None
  1898. if '__many__' in configspec.scalars:
  1899. many = configspec['__many__']
  1900. elif '___many___' in configspec.scalars:
  1901. many = configspec['___many___']
  1902. if many is not None:
  1903. for entry in unvalidated:
  1904. val = section[entry]
  1905. ret_true, ret_false = validate_entry(entry, many, val, False,
  1906. ret_true, ret_false)
  1907. unvalidated = []
  1908. for entry in incorrect_scalars:
  1909. ret_true = False
  1910. if not preserve_errors:
  1911. out[entry] = False
  1912. else:
  1913. ret_false = False
  1914. msg = 'Value %r was provided as a section' % entry
  1915. out[entry] = validator.baseErrorClass(msg)
  1916. for entry in incorrect_sections:
  1917. ret_true = False
  1918. if not preserve_errors:
  1919. out[entry] = False
  1920. else:
  1921. ret_false = False
  1922. msg = 'Section %r was provided as a single value' % entry
  1923. out[entry] = validator.baseErrorClass(msg)
  1924. # Missing sections will have been created as empty ones when the
  1925. # configspec was read.
  1926. for entry in section.sections:
  1927. # FIXME: this means DEFAULT is not copied in copy mode
  1928. if section is self and entry == 'DEFAULT':
  1929. continue
  1930. if section[entry].configspec is None:
  1931. unvalidated.append(entry)
  1932. continue
  1933. if copy:
  1934. section.comments[entry] = configspec.comments.get(entry, [])
  1935. section.inline_comments[entry] = configspec.inline_comments.get(entry, '')
  1936. check = self.validate(validator, preserve_errors=preserve_errors, copy=copy, section=section[entry])
  1937. out[entry] = check
  1938. if check == False:
  1939. ret_true = False
  1940. elif check == True:
  1941. ret_false = False
  1942. else:
  1943. ret_true = False
  1944. section.extra_values = unvalidated
  1945. if preserve_errors and not section._created:
  1946. # If the section wasn't created (i.e. it wasn't missing)
  1947. # then we can't return False, we need to preserve errors
  1948. ret_false = False
  1949. #
  1950. if ret_false and preserve_errors and out:
  1951. # If we are preserving errors, but all
  1952. # the failures are from missing sections / values
  1953. # then we can return False. Otherwise there is a
  1954. # real failure that we need to preserve.
  1955. ret_false = not any(out.values())
  1956. if ret_true:
  1957. return True
  1958. elif ret_false:
  1959. return False
  1960. return out
  1961. def reset(self):
  1962. """Clear ConfigObj instance and restore to 'freshly created' state."""
  1963. self.clear()
  1964. self._initialise()
  1965. # FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
  1966. # requires an empty dictionary
  1967. self.configspec = None
  1968. # Just to be sure ;-)
  1969. self._original_configspec = None
  1970. def reload(self):
  1971. """
  1972. Reload a ConfigObj from file.
  1973. This method raises a ``ReloadError`` if the ConfigObj doesn't have
  1974. a filename attribute pointing to a file.
  1975. """
  1976. if not isinstance(self.filename, basestring):
  1977. raise ReloadError()
  1978. filename = self.filename
  1979. current_options = {}
  1980. for entry in OPTION_DEFAULTS:
  1981. if entry == 'configspec':
  1982. continue
  1983. current_options[entry] = getattr(self, entry)
  1984. configspec = self._original_configspec
  1985. current_options['configspec'] = configspec
  1986. self.clear()
  1987. self._initialise(current_options)
  1988. self._load(filename, configspec)
  1989. class SimpleVal(object):
  1990. """
  1991. A simple validator.
  1992. Can be used to check that all members expected are present.
  1993. To use it, provide a configspec with all your members in (the value given
  1994. will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
  1995. method of your ``ConfigObj``. ``validate`` will return ``True`` if all
  1996. members are present, or a dictionary with True/False meaning
  1997. present/missing. (Whole missing sections will be replaced with ``False``)
  1998. """
  1999. def __init__(self):
  2000. self.baseErrorClass = ConfigObjError
  2001. def check(self, check, member, missing=False):
  2002. """A dummy check method, always returns the value unchanged."""
  2003. if missing:
  2004. raise self.baseErrorClass()
  2005. return member
  2006. def flatten_errors(cfg, res, levels=None, results=None):
  2007. """
  2008. An example function that will turn a nested dictionary of results
  2009. (as returned by ``ConfigObj.validate``) into a flat list.
  2010. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
  2011. dictionary returned by ``validate``.
  2012. (This is a recursive function, so you shouldn't use the ``levels`` or
  2013. ``results`` arguments - they are used by the function.)
  2014. Returns a list of keys that failed. Each member of the list is a tuple::
  2015. ([list of sections...], key, result)
  2016. If ``validate`` was called with ``preserve_errors=False`` (the default)
  2017. then ``result`` will always be ``False``.
  2018. *list of sections* is a flattened list of sections that the key was found
  2019. in.
  2020. If the section was missing (or a section was expected and a scalar provided
  2021. - or vice-versa) then key will be ``None``.
  2022. If the value (or section) was missing then ``result`` will be ``False``.
  2023. If ``validate`` was called with ``preserve_errors=True`` and a value
  2024. was present, but failed the check, then ``result`` will be the exception
  2025. object returned. You can use this as a string that describes the failure.
  2026. For example *The value "3" is of the wrong type*.
  2027. """
  2028. if levels is None:
  2029. # first time called
  2030. levels = []
  2031. results = []
  2032. if res == True:
  2033. return results
  2034. if res == False or isinstance(res, Exception):
  2035. results.append((levels[:], None, res))
  2036. if levels:
  2037. levels.pop()
  2038. return results
  2039. for (key, val) in res.items():
  2040. if val == True:
  2041. continue
  2042. if isinstance(cfg.get(key), dict):
  2043. # Go down one level
  2044. levels.append(key)
  2045. flatten_errors(cfg[key], val, levels, results)
  2046. continue
  2047. results.append((levels[:], key, val))
  2048. #
  2049. # Go up one level
  2050. if levels:
  2051. levels.pop()
  2052. #
  2053. return results
  2054. def get_extra_values(conf, _prepend=()):
  2055. """
  2056. Find all the values and sections not in the configspec from a validated
  2057. ConfigObj.
  2058. ``get_extra_values`` returns a list of tuples where each tuple represents
  2059. either an extra section, or an extra value.
  2060. The tuples contain two values, a tuple representing the section the value
  2061. is in and the name of the extra values. For extra values in the top level
  2062. section the first member will be an empty tuple. For values in the 'foo'
  2063. section the first member will be ``('foo',)``. For members in the 'bar'
  2064. subsection of the 'foo' section the first member will be ``('foo', 'bar')``.
  2065. NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't
  2066. been validated it will return an empty list.
  2067. """
  2068. out = []
  2069. out.extend([(_prepend, name) for name in conf.extra_values])
  2070. for name in conf.sections:
  2071. if name not in conf.extra_values:
  2072. out.extend(get_extra_values(conf[name], _prepend + (name,)))
  2073. return out
  2074. """*A programming language is a medium of expression.* - Paul Graham"""