eaiovnaovbqoebvqoeavibavo 3 S^@sVddlZddlZddlZddlmZmZmZmZddlZddl m Z da edKedLedMedNiZ ddddddddddddddddZ eeeeed Zd d Zd Zd ZdZdZdZdZeZdOZd$Zd%Zd&Zd'd(d'd(d(dd'dddd(d(d) Zd*d+ZGd,d!d!eZGd-d.d.eZ e Z!d/d0Z"Gd1dde#Z$Gd2dde$Z%Gd3dde$Z&Gd4dde'Z(Gd5dde$Z)Gd6dde$Z*Gd7dde$Z+Gd8dde+Z,Gd9dde$Z-Gd:dde+Z.Gd;d d e$Z/Gdd?d?e0Z1Gd@dAdAe0Z2e1e2dBZ3dCdDZ4GdEdFdFe5Z6GdGdde6Z7GdHddeZ8dPdId"Z9ffdJd#Z:dS)QN)BOM_UTF8 BOM_UTF16 BOM_UTF16_BE BOM_UTF16_LE) __version__utf_8utf16_beutf_16utf16_le)r u16utf16zutf-16r utf_16_bezutf-16ber utf_16_lezutf-16leru8utfutf8zutf-8)rr rr NcCstj|jdkS)Nr)BOM_LISTgetlower)encodingr/usr/lib/python3.6/configobj.py match_utf8Dsrz'%s'z"%s"z%sz '"z"""%s"""z'''%s'''DEFAULT_INDENT_TYPEDEFAULT_INTERPOLATIONConfigObjError NestingError ParseErrorDuplicateErrorConfigspecError ConfigObj SimpleValInterpolationErrorInterpolationLoopErrorMissingInterpolationOptionRepeatSectionError ReloadError UnreprError UnknownTypeflatten_errorsget_extra_values configparserz TF) interpolation raise_errors list_values create_empty file_error configspec stringify indent_typerdefault_encodingunreprwrite_empty_valuescCs>tdkrddlad|}tj|}|jdjdjdS)Nrza=)compilerparse getChildren)sprrrgetObjs  r>c@s eZdZdS)r(N)__name__ __module__ __qualname__rrrrr(sc@s\eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)BuildercCstdkrt|jjt|S)N)mr( __class__r?)selforrrbuilds z Builder.buildcCstt|j|jS)N)listmaprGr;)rErFrrr build_ListszBuilder.build_ListcCs|jS)N)value)rErFrrr build_ConstszBuilder.build_ConstcCs6i}tt|j|j}x|D]}t|||<qW|S)N)iterrIrGr;next)rErFdiZelrrr build_Dicts  zBuilder.build_DictcCst|j|S)N)tuplerJ)rErFrrr build_TupleszBuilder.build_TuplecCs6|jdkrdS|jdkrdS|jdkr*dStddS)NNoneTrueTFalseFzUndefined Name)namer()rErFrrr build_Names   zBuilder.build_Namec Cshtt|j|j\}}y t|}Wntk r@tdYnXt|t sX|j dkr`td||S)NZAddg) rHrIrLr;float TypeErrorr( isinstancecomplexreal)rErFr]imagrrr build_Adds zBuilder.build_AddcCs|j|j}t||jS)N)rGexprgetattrZattrname)rErFparentrrr build_Getattrs zBuilder.build_GetattrcCs|j|jd S)Nr)rLr;)rErFrrrbuild_UnarySubszBuilder.build_UnarySubcCs|j|jdS)Nr)rLr;)rErFrrrbuild_UnaryAddszBuilder.build_UnaryAddN) r?r@rArGrJrLrQrSrXr_rcrdrerrrrrBs  rBcCs|s|Sddl}|j|S)Nr)astZ literal_eval)r<rfrrrr6sr6c@seZdZdZdddZdS)rzk This is the base class for all errors that ConfigObj raises. It is a subclass of SyntaxError. NcCs||_||_tj||dS)N)line line_number SyntaxError__init__)rEmessagerirhrrrrkszConfigObjError.__init__)rgNrg)r?r@rA__doc__rkrrrrrsc@seZdZdZdS)rzE This error indicates a level of nesting that doesn't match. N)r?r@rArmrrrrrsc@seZdZdZdS)rz This error indicates that a line is badly written. It is neither a valid ``key = value`` line, nor a valid section marker line. N)r?r@rArmrrrrrsc@seZdZdZddZdS)r&zW A 'reload' operation failed. This exception is a subclass of ``IOError``. cCstj|ddS)Nz#reload failed, filename is not set.)IOErrorrk)rErrrrkszReloadError.__init__N)r?r@rArmrkrrrrr&sc@seZdZdZdS)rz: The keyword or section specified already exists. N)r?r@rArmrrrrrsc@seZdZdZdS)rz7 An error occured whilst parsing a configspec. N)r?r@rArmrrrrrsc@seZdZdZdS)r"z,Base class for the two interpolation errors.N)r?r@rArmrrrrr"sc@seZdZdZddZdS)r#z=Maximum interpolation depth exceeded in string interpolation.cCstj|d|dS)Nz*interpolation loop detected in value "%s".)r"rk)rEoptionrrrrkszInterpolationLoopError.__init__N)r?r@rArmrkrrrrr#sc@seZdZdZdS)r%zk This error indicates additional sections in a section with a ``__many__`` (repeated) section. N)r?r@rArmrrrrr% sc@seZdZdZddZdS)r$z0A value specified for interpolation was missing.cCsd|}tj||dS)Nz%missing option "%s" in interpolation.)r"rk)rEromsgrrrrksz#MissingInterpolationOption.__init__N)r?r@rArmrkrrrrr$sc@seZdZdZdS)r'z An error parsing in unrepr mode.N)r?r@rArmrrrrr'sc@s>eZdZdZejdZdZddZddZ dd Z d d Z d S) InterpolationEnginez A helper class to help perform string interpolation. This class is an abstract base class; its descendants perform the actual work. z %\(([^)]*)\)s%cCs ||_dS)N)section)rErsrrrrk*szInterpolationEngine.__init__cs0j|kr|Sfdd||ji}|S)Nc s||jf|krt|d|||jf<jj|}xz|rj|\}}}|dkrT|}n||||}|j\} } dj|d| ||| df}| t|} jj|| }q2W|||jf=|S)axThe function that does the actual work. ``value``: the string we're trying to interpolate. ``section``: the section in which that string was found ``backtrail``: a dict to keep track of where we've been, to detect and prevent infinite recursion loops This is similar to a depth-first-search algorithm. r8Nrg)rWr#_KEYCREsearch _parse_matchspanjoinlen) keyrKrsZ backtrailmatchkvr<Z replacementstartendZnew_search_start)recursive_interpolaterErrr4s      z>InterpolationEngine.interpolate..recursive_interpolate)_cookiers)rErzrKr)rrEr interpolate/s  ,zInterpolationEngine.interpolatecCs|jjj}d|jj_|j}x^|j|}|dk r\$) | # Two $ signs (?P[_a-z][_a-z0-9]*) | # $name format {(?P[^}]*)} # ${name} format ) cCs\|jdp|jd}|dk r4|j|\}}|||fS|jddk rNd|jdfSd|jdfS)NZnamedZbracedZescaped)rr _delimiter)rEr{rzrKrsrrrrvs  z"TemplateInterpolation._parse_matchN) r?r@rArmrrrr IGNORECASEVERBOSErtrvrrrrrs r)r+templatecGs|j|f|S)N)__new__)clsargsrrr __newobj__src@s$eZdZdZddZddZdDddZd d Zd d Zd dZ dEddZ ddZ dFddZ ddZ efddZddZddZdGddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZeZd*d+Zd,d-ZeZd.e_d/d0Zd1d2Zd3d4ZdHd6d7Zd8d9Z d:d;Z!dd?Z#d@dAZ$dBdCZ%dS)Ira A dictionary-like object that represents a section in a config file. It does string interpolation if the 'interpolation' attribute of the 'main' object is set to True. Interpolation is tried first from this object, then from the 'DEFAULT' section of this object, next from the parent and its 'DEFAULT' section, and so on until the main object is reached. A Section will behave like an ordered dictionary - following the order of the ``scalars`` and ``sections`` attributes. You can use this to change the order of members. Iteration follows the order: scalars, then sections. cCs$tj||d|jj|ddS)Nrr8)dictupdate__dict__)rEstaterrr __setstate__szSection.__setstate__cCst||jf}t|jf|fS)N)rrrrD)rErrrr __reduce__szSection.__reduce__NcCsX|dkr i}tj|||_||_||_||_|jx|jD]\}}|||<q@WdS)z * parent is the section above * depth is the depth level of this section * main is the main ConfigObj * indict is a dictionary to initialise the section with N)rrkrbrdepthrW _initialiseitems)rErbrrindictrWentryrKrrrrks zSection.__init__cCs:g|_g|_i|_i|_d|_g|_i|_g|_d|_dS)NF) scalarssectionscommentsinline_commentsr2defaultsdefault_values extra_values_created)rErrrrszSection._initialisec Csvy |j}Wn^tk rh|jj}|dkr.t}|j}tj|d}|dkrVd|j_|S||}|_YnX|j||S)NTF) Z_interpolation_engineAttributeErrorrr-rrinterpolation_enginesrr)rErzrKZenginerWZclass_rrr _interpolates  zSection._interpolatecsftj}jjrbt|tjr,j|St|trbfddfdd|D}||krb|S|S)z+Fetch the item and do string interpolation.cst|tjrj|S|S)N)r[six string_typesr)r)rzrErr_check/s  z#Section.__getitem__.._checkcsg|] }|qSrr).0r)rrr 3sz'Section.__getitem__..) r __getitem__rr-r[rrrrH)rErzrnewr)rrzrErr(s    zSection.__getitem__Fc CsNt|tjstd|||jkr6g|j|<d|j|<||jkrL|jj|t|trz||krj|j j |t j |||nt|t r| r||kr|j j ||j d}t j ||t|||j||dn||kr|jj ||jjsA version of ``get`` that doesn't bypass string interpolation.N)KeyError)rErzdefaultrrrrsz Section.getcCsx|D]}||||<qWdS)zD A version of update that uses our ``__setitem__``. Nr)rErrrrrrs zSection.updatec Cs:y ||}Wn"tk r.|tkr&|}YnX||=|S)z 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' )rMISSING)rErzrrrrrpops  z Section.popcCs6|j|j}|std|d}||}||=||fS)zPops the first (key,val)z": 'popitem(): dictionary is empty'r)rrr)rEZsequencerzrrrrpopitems zSection.popitemcCs8tj|g|_g|_i|_i|_d|_g|_g|_dS)z A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected N) rclearrrrrr2rr)rErrrrs z Section.clearc Cs.y||Stk r(|||<||SXdS)z:A version of setdefault that sets sequence if appropriate.N)r)rErzrrrr setdefaults zSection.setdefaultcCstt|j|jt|jS)z8D.items() -> list of D's (key, value) pairs, as 2-tuples)rHziprrvalues)rErrrrsz Section.itemscCs |j|jS)zD.keys() -> list of D's keys)rr)rErrrkeyssz Section.keyscsfddjjDS)z D.values() -> list of D's valuescsg|] }|qSrr)rrz)rErrrsz"Section.values..)rr)rEr)rErrszSection.valuescCstt|jS)z=D.iteritems() -> an iterator over the (key, value) items of D)rMrHr)rErrr iteritemsszSection.iteritemscCst|j|jS)z.D.iterkeys() -> an iterator over the keys of D)rMrr)rErrriterkeysszSection.iterkeyscCstt|jS)z2D.itervalues() -> an iterator over the values of D)rMrHr)rErrr itervaluesszSection.itervaluescs0fddddjfddjjDS)zx.__repr__() <==> repr(x)c s*y|Stk r$tj|SXdS)N)r$rr)rz)rErr_getvalsz!Section.__repr__.._getvalz{%s}z, cs$g|]}dt|t|fqS)z%s: %s)repr)rrz)rrrrsz$Section.__repr__..)rxrr)rEr)rrEr__repr__s zSection.__repr__zx.__str__() <==> str(x)cCs`i}xV|D]N}||}t|tr*|j}n&t|tr>t|}nt|trPt|}|||<q W|S)a0 Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() >>> n == a 1 >>> n is a 0 )r[rrrHrR)rEZnewdictr this_entryrrrrs        z Section.dictcCsVxPt|jD]@\}}||krFt||trFt|trF||j|q|||<qWdS)aQ A recursive update - useful for merging config files. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ... [section1] ... option1 = False ... # end of file'''.splitlines() >>> c1 = ConfigObj(b) >>> c2 = ConfigObj(a) >>> c2.merge(c1) >>> c2 ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) N)rHrr[rmerge)rErrzrrrrrs  z Section.mergecCs||jkr|j}n||jkr$|j}n td||j|}||}tj||tj||||j||j|||j |}|j |}|j |=|j |=||j |<||j |<dS)a Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments. zKey "%s" not found.N) rrrindexrrrrinsertrr)rEZoldkeyZnewkeythe_listposrZcommZinline_commentrrrrename,s"          zSection.renameTc Ksi}xttt|jD]b}|j|}y$|||f|}|j|}|||<Wqtk rt|r^n|j|}d||<YqXqWxtt|jD]~}|j|}|ry|||f|Wn.tk r|rƂn|j|}d||<YnX|j|}||j|f||d|||<qW|S)a Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you pass to walk, will be pased on to the function you pass in. Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded. See the encode and decode methods for examples, including functions. .. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) >>> def transform(section, key): ... val = section[key] ... newkey = key.replace('XXXX', 'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}) F)r.call_on_sections)rangeryr Exceptionrwalk) rEZfunctionr.rZkeywargsoutrPrrrrrrJs:/       z Section.walkc Csn||}|dkrdS|dkr dSy(t|tjs6tn|jj|jSWn tk rhtd|YnXdS)a_ Accepts a key as input. The corresponding value must be a string or the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to retain compatibility with Python 2.2. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ``True``. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns ``False``. ``as_bool`` is not case sensitive. Any other input will raise a ``ValueError``. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_bool('a') Traceback (most recent call last): ValueError: Value "fish" is neither True nor False >>> a['b'] = 'True' >>> a.as_bool('b') 1 >>> a['b'] = 'off' >>> a.as_bool('b') 0 TFz$Value "%s" is neither True nor FalseN)r[rrrr_boolsrr)rErzrrrras_bools zSection.as_boolcCs t||S)ai A convenience method which coerces the specified value to an integer. If the value is an invalid literal for ``int``, a ``ValueError`` will be raised. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_int('a') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'fish' >>> a['b'] = '1' >>> a.as_int('b') 1 >>> a['b'] = '3.2' >>> a.as_int('b') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '3.2' )int)rErzrrras_intszSection.as_intcCs t||S)a> A convenience method which coerces the specified value to a float. If the value is an invalid literal for ``float``, a ``ValueError`` will be raised. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_float('a') #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ValueError: invalid literal for float(): fish >>> a['b'] = '1' >>> a.as_float('b') 1.0 >>> a['b'] = '3.2' >>> a.as_float('b') #doctest: +ELLIPSIS 3.2... )rY)rErzrrras_floatszSection.as_floatcCs$||}t|ttfrt|S|gS)aU A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1] >>> a.as_list('a') [1] )r[rRrH)rErzresultrrras_listszSection.as_listcCs2|j|}tj|||||jkr.|jj||S)a Restore (and return) default value for the specified key. This method will only work for a ConfigObj that was created with a configspec and has been validated. If there is no default value for this key, ``KeyError`` is raised. )rrrrr)rErzrrrrrestore_defaults   zSection.restore_defaultcCs:x|jD]}|j|qWx|jD]}||jq"WdS)a' Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created with a configspec and has been validated. It doesn't delete or modify entries without default values. N)rrrrestore_defaults)rErzrsrrrrs  zSection.restore_defaults)NN)F)N)N)TF)&r?r@rArmrrrkrrrrrrrrrrrrrrrrr__iter__rr__str__rrrrrrrrrrrrrrrsH  ;      T,rc@seZdZdZejdejZejdejZejdejZ ejdejZ ejdejZ ejdZ ejdZ ejd Zejd Ze efe efd Zd d d d d d d d dZdFddZddZdGddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZdHd*d+Zd,d-Z d.d/Z!d0d1Z"d2d3Z#d4d5Z$d6d7Z%d8d9Z&d:d;Z'dd?Z)dJd@dAZ*dBdCZ+dDdEZ,dS)Kr z2An object to read, create, and write config files.a^ # line start (\s*) # indentation ( # keyword (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'"=].*?) # no quotes ) \s*=\s* # divider (.*) # value (including list values and comments) $ # line end a=^ (\s*) # 1: indentation ((?:\[\s*)+) # 2: section marker open ( # 3: section name open (?:"\s*\S.*?\s*")| # at least one non-space with double quotes (?:'\s*\S.*?\s*')| # at least one non-space with single quotes (?:[^'"\s].*?) # at least one non-space unquoted ) # section name close ((?:\s*\])+) # 4: section marker close \s*(\#.*)? # 5: optional comment $a^ (?: (?: ( (?: (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\#][^,\#]*?) # unquoted ) \s*,\s* # comma )* # match all list items ending in a comma (if any) ) ( (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\#\s][^,]*?)| # unquoted (?:(?.set_sectionreadz>infile must be a filename, file like object, or list of lines.r8   css|]}t|tjVqdS)N)r[rr)rrhrrr sz"ConfigObj._load..cSsg|]}|jdqS)z )rstrip)rrhrrrrsz#ConfigObj._load..z at line %s.rz2Parsing failed with several errors. First error %s)rr)rrr)$r[rrfilenameospathisfileopen readlinesr1rnr0writerHrRrr _errors_handle_configspecr2rarrrZ _handle_bomendswithnewlinesallAssertionErrorr_parseriryrerrorsconfig) rErr2hZcontentrrhrinforperrorr)rrrsj                    zConfigObj._loadcCs|dkr t}d|_g|_|d|_|d|_|d|_|d|_|d|_|d|_|d|_ |d|_ |d |_ d |_ d|_ |d |_|d |_g|_g|_d|_|jrd |_tj|dS) Nr.r-r/r0r1r3r4rr5Fr7r6)rrrr.r-r/r0r1r3r4rr5BOMrr7r6initial_comment final_commentr2rrr)rErrrrr0s.           zConfigObj._initialisecs0fddddjfddjjDS)Nc s*y|Stk r$tj|SXdS)N)r$rr)rz)rErrrQsz#ConfigObj.__repr__.._getvalzConfigObj({%s})z, cs$g|]}dt|t|fqS)z%s: %s)r)rrz)rrrrWsz&ConfigObj.__repr__..)rxrr)rEr)rrErrPs zConfigObj.__repr__cCsH|jdk r&|jjtkr&|j||jSt|ttfr>|d}n|}t|tjr\|j||jS|jdk r(t|jj}|dkrx8tt j D](\}\}}|sq|j |r|j||SqW|j||jSt |}|j |s|j||jS|t |d}t|ttfr||d<n|}d|_|j||jSxtt j D]\}\}}t|tj s6|j | rfq6n||_|sd|_|t |d}t|ttfr||d<n|}t|tjr|jdSt|tjr|jdjdS|j|dS|j||Sq6Wtjrt|tr|j|dSt|tjr8|jdjdS|j|dSdS)a1 Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.) If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to unicode. NOTE: This method must not be called with an empty ``infile``. Specifying the *wrong* encoding is likely to cause a ``UnicodeDecodeError``. ``infile`` must always be returned as a list of lines, but may be passed in as a single string. Nrr Tzutf-8)rrr_decoder[rHrRrZ text_typeBOMSr startswithBOM_SETryr binary_type splitlinesdecodeZPY2str)rErrhencrrZfinal_encodingnewlinerrrr[s^           zConfigObj._handle_bomcCs&t|tjr|jr|j|jS|SdS)z@Decode ASCII strings to unicode if a self.encoding is specified.N)r[rrrr)rEZaStringrrr_a_to_us zConfigObj._a_to_ucCsxt|tjr|jdSt|tjr@|r6|j|jdS|jdS|rtx.t|D]"\}}t|tjrN|j|||<qNW|S)z Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. T)r[rrrrr enumerate)rErrrPrhrrrrs     zConfigObj._decodecCs&t|tjr|jr|j|jS|SdS)z'Decode element to unicode if necessary.N)r[rrr5r)rErhrrr_decode_elements zConfigObj._decode_elementcCst|tjst|S|SdS)zh Used by ``stringify`` within validate, to turn non-string values into strings. N)r[rrr)rErKrrr_strs zConfigObj._strcCs"|j}|jrd|_g}d}|}t|d}d}d}x||kr|rHg}|d7}||} | j} | sp| jdrd}|j| q6|s||_g}d}d}|jj| } | dk r| j \} } }}}| r|j dkr| |_ | j d}||j dkr|j dt ||q6||jkrHy|j||j}Wn(tk rD|j d t ||w6YnXn<||jkr\|j}n(||jdkrr|}n|j d t ||q6|j|}||kr|j d t||q6t||||d }|||<||j|<||j|<q6|jj| } | dkr|j d j| t||q6| j \} }}| r,|j dkr,| |_ |dddkry|j||||\}}}Wn(tk r|j dt||w6YnjX|jrd}y t|}WnNtk r}z0t|tkrd}nd}|j |t||w6WYdd}~XnXn|jrTd}y t|}WnLtk rP}z.t|tr*d}nd}|j |t||w6WYdd}~XnXnx$||jkr$||jkrt|j}qW|j|kr4|StdS)z Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section. Return a reference to the right section, or raise a SyntaxError. N)rrbrj)rEZsectrrrrr+s    zConfigObj._match_depthcCsB||}|d7}dj||}||||}|jr2||jj|dS)z Handle an error according to the error settings. Either raise the error or store it. The error will have occured at ``cur_index`` r8z{0} at line {1}.N)r.r.rr)rEtextZ ErrorClassrr3rhrlrrrrr*s  zConfigObj._handle_errorcCs4|st|d|dkr0|ddkr0|dd}|S)z%Return an unquoted version of a valuerr8"'r)r9r:r)rj)rErKrrrr,s  zConfigObj._unquotecs|rjr|dkrdS|rjt|ttfrj|s0dSt|dkrRj|ddddSdjfdd |DSt|tjsj rt |}n t d ||sd Sj od |kod |k}|od|krd|kpd |k}|o| od|kod|kod |k}|s| o| }|rhj st }nNd |kr0td|n6|dtkr\|dtkr\d|kr\t }n j|}n j|}|t krd |krj rj|}||S)a Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. * Recursively quote members of a list and return a comma joined list. * Multiline is ``False`` for lists. * Obey list syntax for empty and single member lists. If ``list_values=False`` then the value is only quoted if it contains a ``\n`` (is multiline) or '#'. If ``write_empty_values`` is set, and the value is an empty string, it won't be quoted. rg,r8rF) multilinez, csg|]}j|ddqS)F)r<)_quote)rr)rErrrsz$ConfigObj._quote..zValue "%s" is not a string.z""rr r:r9z#Value "%s" cannot be safely quoted.r)r7r[rHrRryr=rxrrr3rrZr/noquotr wspace_plus_get_single_quote_get_triple_quote)rErKr<Zno_lists_no_quotesZ need_tripleZhash_triple_quoteZcheck_for_singlequotr)rErr=sB     "     zConfigObj._quotecCs4d|krd|krtd|nd|kr,t}nt}|S)Nr:r9z#Value "%s" cannot be safely quoted.)rsquotdquot)rErKrBrrrr@%s zConfigObj._get_single_quotecCsD|jddkr(|jddkr(td||jddkr.) rr/ _nolistvaluer{rjr( _valueexpr, _listvalueexpfindall)rErKr4r/ZsingleZ empty_listr6rr)rErr19s6      zConfigObj._handle_valuec Cs|dd}|dd}|j|d}|j|d}|j|} | dk r`t| j} | j|| S|j|dkrttxD||kr|d7}|d7}||} | j|dkr|| 7}qvPqvWt|j| } | dkrt| j\}} ||| |fS)z9Extract the value, where we are in a multiline situation.Nr#rr8rrr) _triple_quoter{rHr(rrErj) rErKrr3r2rBZnewvalueZ single_lineZ multi_liner4Zretvalrhr6rrrr/js0         zConfigObj._multilinecCst|tszyt|dddd}WnZtk rL}ztd|WYdd}~Xn.tk rx}ztd|WYdd}~XnX||_dS)zParse the configspec.T)r.r1rzParsing configspec failed: %sNzReading configspec failed: %s)r[r rrrnr2)rEr2r7rrrrs  zConfigObj._handle_configspeccCs|j}|jd}t|tr}j|}|j}|r|j| r||}|j|qrW|_|k r|SjdkrF|dkrFjrfdd|D}jrBjdks"tjjjdkrB|s2|jd t|d |d <|SjpRt j!}t"|d ddk r|j#d krt$j%d kr|dkrd}j|j&|}|j'|s||7}t|t(j)r|}n|j*jpڈj+pd}jrjdkst,jrt|}|dk r|j|n"t-jd}|j|WdQRXdS)a~ Write the current ConfigObj as a file tekNico: FIXME: use StringIO instead of real files >>> filename = a.filename >>> a.filename = 'test.ini' >>> a.write() >>> a.filename = filename >>> a == ConfigObj('test.ini', raise_errors=True) 1 >>> import os >>> os.remove('test.ini') Nr z# F)rscsg|]}|jjqSr)encoder)rl)rErrr/sz#ConfigObj.write..rrgrmoderZwin32z rasciiwb).r4rrr-rrr&rrrrrrrlstriprTrr[rrSextendrrRrrrrrrrrrrlineseprarWsysplatformrxrrrrUr5rr)rEZoutfilersrZcsZcspZint_valrhZ stripped_linerQrZ comment_linerr6routputZ output_bytesr r)rErrs                   zConfigObj.writecstdkrtjdkrtdr0ddlm}|_rtjj_jj_jj_jj_jj _ jj _ jj fdd}id}d}fdd j D} fd d j D} fd d j D} xj D]} | dkrq| j ks| jkrZd} d}rf| j krfjj| gj| <jj| dj| <n d} | }|| | || ||\}}qWd}d j krd }nd j krd }|dk rx,| D]$} | }|| ||d||\}}qWg} x<| D]4} d}s d| <nd}d| }j|| <qWx<| D]4} d}sJd| <nd}d| }j|| <q2Wxj D]} kr| dkrqr| jdkr| j| qrrڈjj| gj| <jj| dj| <j| d}|| <|dkrd}n|dkrd}nd}qrW| _r<j rConfigObj.validate..validate_entry..rg)rrZget_default_valuerrbaseErrorClasscheckr[_vdtMissingValuer3rHrRrrr)rspecrraret_true ret_falserdr7)r2rNrpreserve_errorsrsrE validatorrrvalidate_entrys:     z*ConfigObj.validate..validate_entryTcsg|]}|kr|qSrr)rr|)r2rrrsz&ConfigObj.validate..csg|]}|jkr|qSr)r)rr|)rsrrrscsg|]}|jkr|qSr)r)rr|)rsrrrsrM ___many___rgFz"Value %r was provided as a sectionz)Section %r was provided as a single valuer)rirNrs)rMrl)r2rvalidater`rerrrrrr4rPrrrrrrrcrrranyr)rErjrirNrsr`rkrgrhZ unvalidatedZincorrect_sectionsZincorrect_scalarsrrarrOrprdr)r2rNrrirsrErjrrmSs$         -                  zConfigObj.validatecCs |j|jd|_d|_dS)z@Clear ConfigObj instance and restore to 'freshly created' state.N)rrr2r)rErrrreset" szConfigObj.resetcCstt|jtjst|j}i}x$tD]}|dkr2q$t||||<q$W|j}||d<|j|j ||j ||dS)z Reload a ConfigObj from file. This method raises a ``ReloadError`` if the ConfigObj doesn't have a filename attribute pointing to a file. r2N) r[rrrr&rrarrrr)rErZcurrent_optionsrr2rrrreload- s  zConfigObj.reload)NNNNTFTFFTNNFFF)N)T)NN)FFN)-r?r@rArmrrrr-r'rIrJrHZ_single_line_singleZ_single_line_doubleZ_multi_line_singleZ_multi_line_doublerLrrkrrrrrrrrr r+r*r,r=r@rAr1r/rrPrRrSrTrrmrorprrrrr /sx         6`  u  ( G  1#  r O c@s"eZdZdZddZdddZdS) r!a A simple validator. Can be used to check that all members expected are present. To use it, provide a configspec with all your members in (the value given will be ignored). Pass an instance of ``SimpleVal`` to the ``validate`` method of your ``ConfigObj``. ``validate`` will return ``True`` if all members are present, or a dictionary with True/False meaning present/missing. (Whole missing sections will be replaced with ``False``) cCs t|_dS)N)rrc)rErrrrkS szSimpleVal.__init__FcCs|r |j|S)z9A dummy check method, always returns the value unchanged.)rc)rErdmemberrarrrrdV szSimpleVal.checkN)F)r?r@rArmrkrdrrrrr!G s cCs|dkrg}g}|dkr t|S|dks2t|tr^|j|ddd|f|rV|jt|Sxht|jD]X\}}|dkr~qlt|j|tr|j|t |||||ql|j|dd||fqlW|r|jt|S)a An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. (This is a recursive function, so you shouldn't use the ``levels`` or ``results`` arguments - they are used by the function.) Returns a list of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) If ``validate`` was called with ``preserve_errors=False`` (the default) then ``result`` will always be ``False``. *list of sections* is a flattened list of sections that the key was found in. If the section was missing (or a section was expected and a scalar provided - or vice-versa) then key will be ``None``. If the value (or section) was missing then ``result`` will be ``False``. If ``validate`` was called with ``preserve_errors=True`` and a value was present, but failed the check, then ``result`` will be the exception object returned. You can use this as a string that describes the failure. For example *The value "3" is of the wrong type*. NTF) sortedr[rrrrHrrrr))ZcfgresZlevelsresultsrzrrrrr)] s*  csVg}|jfdd|jDx2|jD](}||jkr&|jt|||fq&W|S)a Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a list of tuples where each tuple represents either an extra section, or an extra value. The tuples contain two values, a tuple representing the section the value is in and the name of the extra values. For extra values in the top level section the first member will be an empty tuple. For values in the 'foo' section the first member will be ``('foo',)``. For members in the 'bar' subsection of the 'foo' section the first member will be ``('foo', 'bar')``. NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't been validated it will return an empty list. csg|] }|fqSrr)rrW)_prependrrr sz$get_extra_values..)r[rrr*)ZconfrurrWr)rurr* s   )rN)rr )r r )r r )rrrrrrrr r!r"r#r$r%r&r'r(r)r*)NN);rrr]codecsrrrrrZ_versionrr9rrrrrCrDr>r?rGrFobjectr__all__rrZMAX_INTERPOL_DEPTHrr>rr(rBZ_builderr6rjrrrrnr&rrr"r#r%r$r'rqrrrrrrr r!r)r*rrrrs  7    | i" <