raspberry pi zero based drum machine
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

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