o 9Va ^@sTddlZddlZddlZddlmZmZmZmZddlZddl m Z da edededediZ ddddd d d d d d d d d d d d Z eeeeed ZddZdZdZdZdZdZdZeZdZdZdZdZddddddddddddd ZddZGdd d eZGd!d"d"eZ e Z!d#d$Z"Gd%d&d&e#Z$Gd'd(d(e$Z%Gd)d*d*e$Z&Gd+d,d,e'Z(Gd-d.d.e$Z)Gd/d0d0e$Z*Gd1d2d2e$Z+Gd3d4d4e+Z,Gd5d6d6e$Z-Gd7d8d8e+Z.Gd9d:d:e$Z/Gd;d<dd>e0Z1Gd?d@d@e0Z2e1e2dAZ3dBdCZ4GdDdEdEe5Z6GdFdGdGe6Z7GdHdIdIeZ8dOdJdKZ9dPdMdNZ:dS)QN)BOM_UTF8 BOM_UTF16 BOM_UTF16_BE BOM_UTF16_LE) __version__)utf_8N)utf16_beutf_16)utf16_ler )r r r rr r)r u16utf16zutf-16r utf_16_bezutf-16ber utf_16_lezutf-16leru8utfutf8utf-8)rr rr NcCst|dkS)Nr)BOM_LISTgetlower)encodingr+/usr/lib/python3/dist-packages/configobj.py match_utf8Drz'%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>tdurddlad|}t|}|dddS)Nrza=)compilerparse getChildren)sprrrgetObjs  r@c@s eZdZdS)r*N)__name__ __module__ __qualname__rrrrr*sr*c@s\eZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS)BuildercCstdur t|jjt|SN)mr* __class__rAselforrrbuilds z Builder.buildcCstt|j|SrE)listmaprKr=rHrrr build_ListzBuilder.build_ListcCs|jSrE)valuerHrrr build_ConstszBuilder.build_ConstcCs2i}tt|j|}|D]}t|||<q|SrE)iterrMrKr=next)rIrJdielrrr build_Dicts zBuilder.build_DictcCst||SrE)tuplerNrHrrr build_TupleszBuilder.build_TuplecCs2|jdkrdS|jdkrdS|jdkrdStd)NNoneTrueTFalseFzUndefined Name)namer*rHrrr build_Names   zBuilder.build_NamecCs`tt|j|\}}zt|}Wn tytdwt|tr(|j dkr,td||S)NAddg) rLrMrQr=float TypeErrorr* isinstancecomplexreal)rIrJrdimagrrr build_Adds  zBuilder.build_AddcCs||j}t||jSrE)rKexprgetattrattrname)rIrJparentrrr build_Getattrs  zBuilder.build_GetattrcCs||d SNrrQr=rHrrrbuild_UnarySubrOzBuilder.build_UnarySubcCs||dSrlrmrHrrrbuild_UnaryAddrzBuilder.build_UnaryAddN) rArBrCrKrNrQrWrYr^rfrkrnrorrrrrDs   rDcCs|s|Sddl}||Srl)ast literal_eval)r>rprrrr8s r8c@seZdZdZdddZdS)rzk This is the base class for all errors that ConfigObj raises. It is a subclass of SyntaxError. NcCs||_||_t||dSrE)line line_number SyntaxError__init__)rImessagertrsrrrrvszConfigObjError.__init__)rrNrrrArBrC__doc__rvrrrrrsrc@eZdZdZdS)rzE This error indicates a level of nesting that doesn't match. NrArBrCryrrrrrrc@rz)rz This error indicates that a line is badly written. It is neither a valid ``key = value`` line, nor a valid section marker line. Nr{rrrrrr|rc@eZdZdZddZdS)r(zW A 'reload' operation failed. This exception is a subclass of ``IOError``. cCst|ddS)Nz#reload failed, filename is not set.)IOErrorrvrIrrrrvszReloadError.__init__Nrxrrrrr(s r(c@rz)r z: The keyword or section specified already exists. Nr{rrrrr r|r c@rz)r!z7 An error occured whilst parsing a configspec. Nr{rrrrr!r|r!c@rz)r$z,Base class for the two interpolation errors.Nr{rrrrr$r|r$c@r})r%z=Maximum interpolation depth exceeded in string interpolation.cCst|d|dS)Nz*interpolation loop detected in value "%s".r$rv)rIoptionrrrrvszInterpolationLoopError.__init__Nrxrrrrr%s r%c@rz)r'zk This error indicates additional sections in a section with a ``__many__`` (repeated) section. Nr{rrrrr' r|r'c@r})r&z0A value specified for interpolation was missing.cCsd|}t||dS)Nz%missing option "%s" in interpolation.r)rIrmsgrrrrvsz#MissingInterpolationOption.__init__Nrxrrrrr&s r&c@rz)r)z An error parsing in unrepr mode.Nr{rrrrr)r|r)c@s>eZdZdZedZdZddZddZ 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. %\(([^)]*)\)s%cCs ||_dSrEsection)rIrrrrrv*s zInterpolationEngine.__init__cs0j|vr|Sfdd||ji}|S)Nc s||jf|vr t|d|||jf<j|}|rU|\}}}|dur)|}n||||}|\} } d|d| ||| df}| t|} j|| }|s|||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. r:Nrr)r]r%_KEYCREsearch _parse_matchspanjoinlen) keyrPr backtrailmatchkvr> replacementstartendnew_search_startrecursive_interpolaterIrrr4s       z>InterpolationEngine.interpolate..recursive_interpolate)_cookier)rIrrPrrr interpolate/s ,zInterpolationEngine.interpolatecCs|jjj}d|jj_|j} ||}|durt|tsn|di|}|dur0t|ts0n |j|ur6n|j}q||jj_|durGt|||fS)zHelper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. FTNDEFAULT)rmainr/rrbSectionrjr&)rIr save_interpcurrent_sectionvalrrr_fetchds$     zInterpolationEngine._fetchcCst)aImplementation-dependent helper function. Will be passed a match object corresponding to the interpolation key we just found (e.g., "%(foo)s" or "$foo"). Should look up that key in the appropriate config file section (using the ``_fetch()`` helper function) and return a 3-tuple: (key, value, section) ``key`` is the name of the key we're looking for ``value`` is the value found for that key ``section`` is a reference to the section where it was found ``key`` and ``section`` should be None if no further interpolation should be performed on the resulting value (e.g., if we interpolated "$$" and returned "$"). )NotImplementedError)rIrrrrrsz InterpolationEngine._parse_matchN) rArBrCryrecompilerrrvrrrrrrrrs 5 "rc@s&eZdZdZdZedZddZdS)ConfigParserInterpolationzBehaves like ConfigParser.rrcCs"|d}||\}}|||fS)Nr:)grouprrIrrrPrrrrrs  z&ConfigParserInterpolation._parse_matchN) rArBrCryrrrrrrrrrrs   rc@s4eZdZdZdZdZedejej BZ ddZ dS)TemplateInterpolationzBehaves like string.Template.$z \$(?: (?P\$) | # Two $ signs (?P[_a-z][_a-z0-9]*) | # $name format {(?P[^}]*)} # ${name} format ) cCs\|dp |d}|dur||\}}|||fS|ddur'd|jdfSd|dfS)Nnamedbracedescaped)rr _delimiterrrrrrs  z"TemplateInterpolation._parse_matchN) rArBrCryrrrr IGNORECASEVERBOSErrrrrrrs  r)r-templatecGs|j|g|RSrE)__new__)clsargsrrr __newobj__src@s(eZdZdZddZddZdDddZd d Zd d Zd dZ dEddZ ddZ dFddZ ddZ efddZddZddZdFddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZeZd*d+Zd,d-ZeZd.e_d/d0Zd1d2Zd3d4Z 5 dGd6d7Zd8d9Z d:d;Z!dd?Z#d@dAZ$dBdCZ%dS)Hra 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$t||d|j|ddS)Nrr:)dictupdate__dict__rIstaterrr __setstate__szSection.__setstate__cCst||jf}t|jf|fSrE)rrrrGrrrr __reduce__szSection.__reduce__NcCsT|duri}t|||_||_||_||_||D]\}}|||<qdS)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)rrvrjrdepthr] _initialiseitems)rIrjrrindictr]entryrPrrrrvs  zSection.__init__cCs:g|_g|_i|_i|_d|_g|_i|_g|_d|_dS)NF) scalarssectionscommentsinline_commentsr4defaultsdefault_values extra_values_createdrrrrrs zSection._initialisecCsxz|j}Wn0ty5|jj}|dkrt}|}t|d}|dur,d|j_|YS||}|_Ynw|||S)NTF) _interpolation_engineAttributeErrorrr/rrinterpolation_enginesrr)rIrrPenginer]class_rrr _interpolates    zSection._interpolatecsft}jjr1t|tjr|St|tr1fddfdd|D}||kr1|S|S)z+Fetch the item and do string interpolation.cst|tjr |S|SrE)rbsix string_typesr)r)rrIrr_check/s  z#Section.__getitem__.._checkcsg|]}|qSrr).0r)rrr 3z'Section.__getitem__..) r __getitem__rr/rbrrrrL)rIrrnewr)rrrIrr(s    zSection.__getitem__Fc CsDt|tjs td|||jvrg|j|<d|j|<||jvr&|j|t|tr>||vr5|j |t |||dSt|t re|se||vrO|j ||j d}t ||t|||j||ddS||vro|j ||jjst|tjrznt|ttfr|D]}t|tjstd|qntd|t |||dS)a Correctly set a value. Making dictionary values Section instances. (We have to special case 'Section' instances - which are also dicts) Keys must be strings. Values need only be strings (or lists of strings) if ``main.stringify`` is set. ``unrepr`` must be set when setting a value to a dictionary, without creating a new sub-section. zThe key "%s" is not a string.rrr:)rr]zValue is not a string "%s".N)rbrr ValueErrorrrrremoverrappendr __setitem__rrrr5rLrXra)rIrrPr8 new_depthrrrrr9sN                zSection.__setitem__cCsDt||||jvr|j|n|j||j|=|j|=dS)z-Remove items from the sequence when deleting.N)r __delitem__rrrrrrIrrrrrts    zSection.__delitem__cCs"z||WSty|YSw)z>A version of ``get`` that doesn't bypass string interpolation.KeyErrorrIrdefaultrrrrs   z Section.getcCs|D]}||||<qdS)zD A version of update that uses our ``__setitem__``. Nr)rIrrrrrrszSection.updatecCs:z||}Wnty|tur|}Y|Sw||=|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)rIrrrrrrpops  z Section.popcCs6|j|j}|s td|d}||}||=||fS)zPops the first (key,val)z": 'popitem(): dictionary is empty'r)rrr)rIsequencerrrrrpopitems zSection.popitemcCs8t|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) rclearrrrrr4rrrrrrrs  z Section.clearcCs.z||WSty|||<||YSw)z:A version of setdefault that sets sequence if appropriate.rrrrr setdefaults    zSection.setdefaultcCstt|j|jt|S)z8D.items() -> list of D's (key, value) pairs, as 2-tuples)rLziprrvaluesrrrrrsz Section.itemscCs |j|jS)zD.keys() -> list of D's keysrrrrrrkeyss z Section.keyscsfddjjDS)z D.values() -> list of D's valuescsg|]}|qSrrrrrrrrrz"Section.values..rrrrrrszSection.valuescCtt|S)z=D.iteritems() -> an iterator over the (key, value) items of D)rRrLrrrrr iteritemszSection.iteritemscCst|j|jS)z.D.iterkeys() -> an iterator over the keys of D)rRrrrrrriterkeysrzSection.iterkeyscCr)z2D.itervalues() -> an iterator over the values of D)rRrLrrrrr itervaluesrzSection.itervaluesc0fddddfddjjDS)zx.__repr__() <==> repr(x)c*z|WStyt|YSwrEr&rrrrrr_getval   z!Section.__repr__.._getvalz{%s}, c$g|]}dt|t|fqSz%s: %sreprrrrrrz$Section.__repr__..rrrrrrrIr__repr__s   zSection.__repr__zx.__str__() <==> str(x)cCs\i}|D]'}||}t|tr|}nt|trt|}n t|tr't|}|||<q|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 )rbrrrLrX)rInewdictr this_entryrrrrs       z Section.dictcCsRt|D] \}}||vr"t||tr"t|tr"|||q|||<qdS)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)rLrrbrmerge)rIrrrrrrrs z Section.mergecCs||jvr |j}n||jvr|j}ntd|||}||}t||t|||||||||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)rIoldkeynewkeythe_listposrcomminline_commentrrrrename,s"          zSection.renameTc Ksi}tt|jD]0}|j|}z|||fi|}|j|}|||<Wq ty9|r.|j|}d||<Yq wtt|jD]?}|j|}|rpz |||fi|Wntyj|r_|j|}d||<Ynw|j|}||j|f||d|||<qA|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)r0call_on_sections)rangerr Exceptionrwalk) rIfunctionr0rkeywargsoutrUrrrrrrJsD/            z Section.walkcCs`||}|dkr dS|dkrdSzt|tjst|jj|WSty/td|w)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 False)rbrrrr_boolsrr)rIrrrrras_bools   zSection.as_boolcC 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' )intrrrras_ints zSection.as_intcCr)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... )r`rrrras_floats zSection.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] )rbrXrL)rIrresultrrras_listszSection.as_listcCs2|j|}t|||||jvr|j||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. )rrrrrrrrrrestore_defaults   zSection.restore_defaultcCs2|jD]}||q|jD]}||qdS)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)rIrrrrrrs  zSection.restore_defaultsNNFrE)TF)&rArBrCryrrrvrrrrrrrrrrrrrrrrr__iter__rr__str__rrr rrrrrrrrrrrrsL  ;      U, rc @seZdZdZedejZedejZedejZ edejZ edejZ edZ edZ ed Zed Ze efe efd Zd d d d d d d d dZ  dFddZddZdGddZddZddZddZddZddZd 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.)  ) rAr@css|] }t|tjVqdSrE)rbrrrrsrrr sz"ConfigObj._load..cSsg|]}|dqS)rB)rstriprCrrrrz#ConfigObj._load..z at line %s.rr:z2Parsing failed with several errors. First error %s)#rbrrfilenameospathisfileopen readlinesr3r~r2writerLrXrr"_errors_handle_configspecr4rhrr>ra _handle_bomendswithnewlinesallr_parsertrrerrorsconfig) rIr4r4hcontentrrsrinforerrorrr<rr3st                  zConfigObj._loadcCs|durt}d|_g|_|d|_|d|_|d|_|d|_|d|_|d|_|d|_ |d|_ |d |_ d |_ d|_ |d |_|d |_g|_g|_d|_|jrXd |_t|dS) Nr0r/r1r2r3r5r6rr7Fr9r8)r1rGrNr0r/r1r2r3r5r6rr7BOMrRr9r8initial_comment final_commentr4r-rr)rIr5rrrr0s.           zConfigObj._initialisecr)NcrrErrrrrrQrz#ConfigObj.__repr__.._getvalzConfigObj({%s})rcrrrrrrrrWrz&ConfigObj.__repr__..rrrrrrPs  zConfigObj.__repr__cCs4|jdur|jtvr|||jSt|ttfr|d}n|}t|tjr.|||jS|jdurt|j}|dkrbtt D]\}\}}|sMqD| |rZ|||SqD|||jSt |}| |sr|||jS|t |d}t|ttfr||d<n|}d|_|||jStt D]\\}\}}t|tjr| |sq||_|sd|_|t |d}t|ttfr||d<n|}t|tjr|dSt|tjr|ddS||dS|||Stjrt|tr||dSt|tjr|ddS||dS)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 Tr)rrr_decoderbrLrXr text_typeBOMSr startswithBOM_SETrr[ binary_type splitlinesdecodePY2str)rIr4rsencr[rfinal_encodingnewlinerrrrP[s`            zConfigObj._handle_bomcC"t|tjr|jr||jS|S)z@Decode ASCII strings to unicode if a self.encoding is specified.)rbrrcrre)rIaStringrrr_a_to_u zConfigObj._a_to_ucCstt|tjr |dSt|tjr |r||dS|dS|r8t|D]\}}t|tjr7||||<q&|S)z Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. T)rbrrrdrcre enumerate)rIr4rrUrsrrrr^s     zConfigObj._decodecCrk)z'Decode element to unicode if necessary.)rbrrcr7re)rIrsrrr_decode_elementrnzConfigObj._decode_elementcCst|tjs t|S|S)zh Used by ``stringify`` within validate, to turn non-string values into strings. )rbrrrgrIrPrrr_strs zConfigObj._strc Cs|j}|jr d|_g}d}|}t|d}d}d}||kr|r"g}|d7}||} | } | r5| dr=d}|| q|sF||_g}d}d}|j| } | dur| \} } }}}| re|j dure| |_ | d}|| dkrz| d t ||q||jkrz |||j}Wn-ty| d t ||Yqw||jkr|j}n||jdkr|}n | d t ||q||}||vr| d t||qt||||d }|||<||j|<||j|<q|j| } | dur| d| t||n| \} }}| r|j dur| |_ |dddvrfz |||||\}}}Wnty0| dt||Yqw|jred}zt|}Wnwtyd}zt|tkrPd}nd}| |t||WYd}~qd}~wwnO|jrd}zt|}WnBty}zt|trd}nd}| |t||WYd}~qd}~wwz | |\}}Wnty| dt||Yqw||}||vr| dt||q|j!||dd||j|<||j|<q||ks|j durd|_ |s|js||_n|s||_"||_dS)zActually parse the config file.Fr:r?#TN[]z Cannot compute the section depthzCannot compute nesting levelzSection too nestedzDuplicate section name)r]z=Invalid line ({0!r}) (matched as neither section nor keyword))r$r#zParse error in multiline valuerrzUnknown name or type in valuez+Parse error from unrepr-ing multiline valuez!Parse error from unrepr-ing valuezParse error in valuezDuplicate keyword name)r8)#r1r8rstriprarr\_sectionmarkerrgroupsr6count _handle_errorrr _match_depthrjru_unquoter rrr_keywordformatr _multilinertyper*r)rb _handle_valuerr])rIr4temp_list_values comment_list done_startr;maxline cur_index reset_commentrsslinematindent sect_open sect_name sect_closecomment cur_depthrjrrPerrrrrTs0                           zConfigObj._parsecCs>||jkr||jur t|j}||jks|j|kr|St)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. )rrjru)rIsectrrrrr|s   zConfigObj._match_depthcCsB||}|d7}d||}||||}|jr||j|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`` r:z{0} at line {1}.N)rr0rNr)rItext ErrorClassr4rrsrwrZrrrr{s  zConfigObj._handle_errorcCs4|st|d|dkr|ddvr|dd}|S)z%Return an unquoted version of a valuerr?)"'r:)rurqrrrr}s  zConfigObj._unquotecs|r jr |dkr dS|r5t|ttfr5|sdSt|dkr)j|ddddSdfdd |DSt|tjsIj rCt |}nt d ||sMd Sj oXd |voXd |v}|ofd|vrcd|vpfd |v}|ow| owd|vowd|vowd |v}|s}| o| }|rj st }n(d |vrtd||dtvr|dtvrd|vrt }n |}n|}|t krd |vrj r|}||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. rr,r:rF multilinercsg|] }j|ddqS)Fr)_quoterrrrrrsz$ConfigObj._quote..zValue "%s" is not a string.""rArsrr#Value "%s" cannot be safely quoted.r?)r9rbrLrXrrrrrr5rgrar1noquotr wspace_plus_get_single_quote_get_triple_quote)rIrPrno_lists_no_quotes need_triplehash_triple_quotecheck_for_singlequotrrrrsD    "      zConfigObj._quotecCs4d|vrd|vrtd|d|vrt}|St}|S)Nrrr)rsquotdquotrIrPrrrrr%s zConfigObj._get_single_quotecCsF|ddkr|ddkrtd||ddkrt}|St}|S)Nr$r?r#r)findrtdquottsquotrrrrr/s zConfigObj._get_triple_quotecsjr|dfSjsj|}|durt|Sj|}|dur(t|\}}}}|dkr;|dur;t|durCg|fS|durW|rN|sNd}n |pQd}|}|dkr_||fSj |}fdd|D}|durw||g7}||fS)z Given a value string, unquote, remove comment, handle lists. (including empty and single member lists) rrNrcg|]}|qSr)r}rrrrrdrFz+ConfigObj._handle_value..) r-r1 _nolistvaluerrury _valueexpr} _listvalueexpfindall)rIrPrr1single empty_listrr rrrr9s6     zConfigObj._handle_valuec Cs|dd}|dd}|j|d}|j|d}||} | dur0t| } | || S||dkr:t||kr[|d7}|d7}||} | |dkrV|| 7}nn||ks>t|| } | durjt| \}} ||| |fS)z9Extract the value, where we are in a multiline situation.Nrvrr:r?rA) _triple_quoterrLryrrru) rIrPr4rrrnewvalue single_line multi_linerretvalrsrrrrrjs2        zConfigObj._multilinec Cspt|ts3z t|dddd}Wn#ty!}ztd|d}~wty2}ztd|d}~ww||_dS)zParse the configspec.T)r0r3r-zParsing configspec failed: %sNzReading configspec failed: %s)rbr"rr!r~r4)rIr4rrrrrOs     zConfigObj._handle_configspeccCs|j}|d}t|tr|jD] }||vr|||_q|jD]8}|dkr&q||vrIi||<d||_|rI|j|g|j|<|j|d|j|<t||trW||||_qdS)z Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ __many__TrrN) r4rrbrrrrrr)rIrcopyr4manyrrrr_set_configspecs(      zConfigObj._set_configspeccCsN|js |||}nt|}d|||j|dd|d|||fS)z.Write an individual line, for the write method %s%s%s%s%sFrz = )r8rprrrm)rI indent_stringrrrrrrr _write_lineszConfigObj._write_linecCs<d||d||j||dd|d|||fS)zWrite a section marker linerrtFrru)rmrrp)rIrrrrrrr _write_markers   zConfigObj._write_markercCs.|sdS|j}|ds||d7}||S)zDeal with a comment.rrrsz # )r6rarm)rIrrrrr_handle_comments  zConfigObj._handle_commentc s6jdurt_g}d}d}|dur?j}d_}jD]}|}|}|r9||s9||}||q#j|j } |j |j D][} | |j vrSqK|j | D]} | } | rl| |sl|| } || | qX|| } |j| } t| tr|| | j | | |j| dqK|| | | | qK|ur͈jD]}|}|}|r||s||}||q|_|ur|Sjdur|durjrfdd|D}jrjdustjdkr|s|d t|d |d <|Sjpt j!}t"|d ddur3|j#d kr3t$j%d kr3|dkr3d}|&|}|'|sE||7}t|t(j)rO|}n |*jpZj+pZd}jrpjduslt,jrpt|}|dur|||dSt-jd}||WddS1swYdS)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') Nrsz# Frcsg|]}|jqSr)encoder)rlrrrr/z#ConfigObj.write..rrrrmoder9win32rBrAasciiwb).r6rrmr/r\rprwrarrrrrrlstriprrrbrrextendrMrr]rGrr[rrrrrRrHlineseprhrsysplatformrrQrrcrr7rrK)rIoutfilerrcscspint_valrs stripped_linerr comment_linerrrjoutput output_bytesrWrrrrMs                  $zConfigObj.writecsNdur:jdur tdrddlm}|_r:jj_jj_jj_jj_jj _ jj _ j fdd}id}d}fdd j D} fd d j D} fd d j D} j D]D} | d vr}qv| j vs| jvrd} d}r| j vrj| gj| <j| d j| <nd} | }|| | || ||\}}qvd}dj vrLjd}n dj vrЈd}|dur| D]} | }|| ||d||\}}qg} | D]} d}sd| <qd}d| }|| <q| D]} d}sd| <qd}d| }|| <qj D]X} ur4| dkr4q&| jdurC| | q&rZj| gj| <j| d j| <j| d}|| <|dkrrd}q&|dkr{d}q&d}q&| _rjsd}|rrrt }|rdS|rdSS)a; Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(validator) (Normally having previously passed in the configspec when the ConfigObj was created - you can dynamically assign a dictionary of checks to the ``configspec`` attribute of a section though). It returns ``True`` if everything passes, or a dictionary of pass/fails (True/False). If every member of a subsection passes, it will just have the value ``True``. (It also returns ``False`` if all members fail). In addition, it converts the values from strings to their native types if their checks pass (and ``stringify`` is set). If ``preserve_errors`` is ``True`` (``False`` is default) then instead of a marking a fail with a ``False``, it will preserve the actual exception object. This can contain info about the reason for failure. For example the ``VdtValueTooSmallError`` indicates that the value supplied was too small. If a value (or section) is missing it will still be marked as ``False``. You must have the validate module to use ``preserve_errors=True``. You can then use the ``flatten_errors`` function to turn your nested results dictionary into a flattened list of failures - useful for displaying meaningful error messages. NzNo configspec supplied.r)VdtMissingValuec sBj|dz |j|<Wn ttjfy Ynwz j|||d}Wn+jyV}zrConfigObj.validate..validate_entry..rr)rrget_default_valuerrbaseErrorClasscheckrb_vdtMissingValuer5rLrXrrrr)rspecrrret_true ret_falserrr4rrpreserve_errorsrrI validatorrrvalidate_entrysD        z*ConfigObj.validate..validate_entryTcsg|]}|vr|qSrrrr)r4rrrrz&ConfigObj.validate..cg|] }|jvr|qSr)rrrrrrcrr)rrrrrrr)r ___many___rrFrrz"Value %r was provided as a sectionz)Section %r was provided as a single valuer)rrr)r4rvalidaterrr\r]rr[rRr6rrrrrrrrrrranyr)rIrrrrrrrr unvalidatedincorrect_sectionsincorrect_scalarsrrrrrrrrrrSs$         -                zConfigObj.validatecCs ||d|_d|_dS)z@Clear ConfigObj instance and restore to 'freshly created' state.N)rrr4r2rrrrreset" s zConfigObj.resetcCspt|jtjs t|j}i}tD]}|dkrqt||||<q|j}||d<|| || ||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. r4N) rbrGrrr(r1rhr2rrr3)rIrGcurrent_optionsrr4rrrreload- s zConfigObj.reload)NNNNTFTFFTNNFFFrE)Tr)FFN)-rArBrCryrrrr~rxrrr_single_line_single_single_line_double_multi_line_single_multi_line_doublerrrvr3rrrPrmr^rprrrTr|r{r}rrrrrrOrrrrrMrrrrrrrr"/s         : `  u  ( G  1# r P r"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|_dSrE)rrrrrrrvS s zSimpleVal.__init__FcCs|r||S)z9A dummy check method, always returns the value unchanged.)r)rIrmemberrrrrrV szSimpleVal.checkNr )rArBrCryrvrrrrrr#G s r#cCs|durg}g}|dkrt|S|dkst|tr/||ddd|f|r+|t|St|D],\}}|dkr>q5t||trU||t |||||q5||dd||fq5|rh|t|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) sortedrbrrrrLrrrr+)cfgreslevelsresultsrrrrrr+] s*  r+rcsRg}|fdd|jD|jD]}||jvr&|t|||fq|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)rr]_prependrrr rz$get_extra_values..)rrrr,)confrrr]rrrr, s  r,r)r);rHrrcodecsrrrrr_versionrr;r`rrbrrrrrrrobjectr__all__rrMAX_INTERPOL_DEPTHr1r@rr*rD_builderr8rurrrr~r(r r!r$r%r'r&r)rrrrrrrr"r#r+r,rrrrs    7    | i"  <