Shuvit game master repo. http://shuvit.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

configobj.py 88KB

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