a S^@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.9/site-packages/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>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)BuildercCstdurt|jjt|SN)mr) __class__r@selforrrbuilds z Builder.buildcCstt|j|SrD)listmaprJr<rGrrr build_ListszBuilder.build_ListcCs|jSrD)valuerGrrr build_ConstszBuilder.build_ConstcCs2i}tt|j|}|D]}t|||<q|SrD)iterrLrJr<next)rHrIdielrrr build_Dicts zBuilder.build_DictcCst||SrD)tuplerMrGrrr build_TupleszBuilder.build_TuplecCs6|jdkrdS|jdkrdS|jdkr*dStddS)NNoneTrueTFalseFzUndefined Name)namer)rGrrr build_Names   zBuilder.build_NamecCsdtt|j|\}}z t|}Wnty>tdYn0t|trT|j dkr\td||S)NZAddg) rKrLrOr<float TypeErrorr) isinstancecomplexreal)rHrIraimagrrr build_Adds  zBuilder.build_AddcCs||j}t||jSrD)rJexprgetattrattrname)rHrIparentrrr build_Getattrs zBuilder.build_GetattrcCs||d SNrrOr<rGrrrbuild_UnarySubszBuilder.build_UnarySubcCs||dSrirjrGrrrbuild_UnaryAddszBuilder.build_UnaryAddN) r@rArBrJrMrOrUrWr\rcrhrkrlrrrrrCs  rCcCs|s|Sddl}||Sri)astZ literal_eval)r=rmrrrr7sr7c@seZdZdZdddZdS)rzk This is the base class for all errors that ConfigObj raises. It is a subclass of SyntaxError. NcCs||_||_t||dSrD)line line_number SyntaxError__init__)rHmessagerprorrrrrszConfigObjError.__init__)rnNrnr@rArB__doc__rrrrrrrsrc@seZdZdZdS)rzE This error indicates a level of nesting that doesn't match. Nr@rArBrurrrrrsrc@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. Nrvrrrrrsrc@seZdZdZddZdS)r'zW A 'reload' operation failed. This exception is a subclass of ``IOError``. cCst|ddS)Nz#reload failed, filename is not set.)IOErrorrrrHrrrrrszReloadError.__init__Nrtrrrrr'sr'c@seZdZdZdS)rz: The keyword or section specified already exists. Nrvrrrrrsrc@seZdZdZdS)r z7 An error occured whilst parsing a configspec. Nrvrrrrr sr c@seZdZdZdS)r#z,Base class for the two interpolation errors.Nrvrrrrr#sr#c@seZdZdZddZdS)r$z=Maximum interpolation depth exceeded in string interpolation.cCst|d|dS)Nz*interpolation loop detected in value "%s".r#rr)rHoptionrrrrrszInterpolationLoopError.__init__Nrtrrrrr$sr$c@seZdZdZdS)r&zk This error indicates additional sections in a section with a ``__many__`` (repeated) section. Nrvrrrrr& sr&c@seZdZdZddZdS)r%z0A value specified for interpolation was missing.cCsd|}t||dS)Nz%missing option "%s" in interpolation.ry)rHrzmsgrrrrrsz#MissingInterpolationOption.__init__Nrtrrrrr%sr%c@seZdZdZdS)r(z An error parsing in unrepr mode.Nrvrrrrr(sr(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 ||_dSrDsection)rHrrrrrr*szInterpolationEngine.__init__cs0j|vr|Sfdd||ji}|S)Nc s||jf|vrt|d|||jf<j|}|r|\}}}|durR|}n||||}|\} } d|d| ||| df}| t|} j|| }q0|||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. r9Nrn)r[r$_KEYCREsearch _parse_matchspanjoinlen) keyrNrZ backtrailmatchkvr=Z replacementstartendZnew_search_startrecursive_interpolaterHrrr4s      z>InterpolationEngine.interpolate..recursive_interpolate)_cookier)rHrrNrrr interpolate/s  ,zInterpolationEngine.interpolatecCs|jjj}d|jj_|j}||}|dur8t|ts8qr|di|}|dur^t|ts^qr|j|urjqr|j}q||jj_|durt|||fS)zHelper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. FNDEFAULT)rmainr.rr_Sectionrgr%)rHrZ save_interpZcurrent_sectionvalrrr_fetchds      zInterpolationEngine._fetchcCs tdS)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 "$"). N)NotImplementedError)rHrrrrrsz InterpolationEngine._parse_matchN) r@rArBrurecompilerrrrrrrrrrrr|s 5"r|c@s&eZdZdZdZedZddZdS)ConfigParserInterpolationzBehaves like ConfigParser.r~r}cCs"|d}||\}}|||fS)Nr9)grouprrHrrrNrrrrrs z&ConfigParserInterpolation._parse_matchN) r@rArBrurrrrrrrrrrs 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}|dur4||\}}|||fS|ddurNd|jdfSd|dfS)NZnamedZbracedZescaped)rr _delimiterrrrrrs  z"TemplateInterpolation._parse_matchN) r@rArBrurrrr IGNORECASEVERBOSErrrrrrrs r)r,templatecGs|j|g|RSrD)__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$t||d|j|ddS)Nrr9)dictupdate__dict__rHstaterrr __setstate__szSection.__setstate__cCst||jf}t|jf|fSrD)rrrrFrrrr __reduce__szSection.__reduce__NcCsT|dur i}t|||_||_||_||_||D]\}}|||<q>dS)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)rrrrgrdepthr[ _initialiseitems)rHrgrrindictr[entryrNrrrrrs zSection.__init__cCs:g|_g|_i|_i|_d|_g|_i|_g|_d|_dS)NF) scalarssectionscommentsinline_commentsr3defaultsdefault_values extra_values_createdrxrrrrszSection._initialisecCsxz |j}Wn`tyj|jj}|dkr,t}|}t|d}|durXd|j_|YS||}|_Yn0|||S)NTF) Z_interpolation_engineAttributeErrorrr.rrinterpolation_enginesrr)rHrrNZenginer[class_rrr _interpolates   zSection._interpolatecsft}jjrbt|tjr,|St|trbfddfdd|D}||krb|S|S)z+Fetch the item and do string interpolation.cst|tjr|S|SrD)r_six string_typesr)r)rrHrr_check/s  z#Section.__getitem__.._checkcsg|] }|qSrr).0r)rrr 3z'Section.__getitem__..) r __getitem__rr.r_rrrrK)rHrrnewr)rrrHrr(s    zSection.__getitem__Fc CsHt|tjstd|||jvr6g|j|<d|j|<||jvrL|j|t|trz||vrj|j |t |||nt|t r|s||vr|j ||j d}t ||t|||j||dn~||vr|j ||jjs6t|tjrnDt|ttfr*|D] }t|tjstd|qn td|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.rnr9)rr[zValue is not a string "%s".N)r_rr ValueErrorrrrremoverrappendr __setitem__rrrr4rKrVr^)rHrrNr7Z new_depthrrrrr9sJ                zSection.__setitem__cCsDt||||jvr$|j|n |j||j|=|j|=dS)z-Remove items from the sequence when deleting.N)r __delitem__rrrrrrHrrrrrts    zSection.__delitem__cCs&z ||WSty |YS0dS)z>A version of ``get`` that doesn't bypass string interpolation.NKeyErrorrHrdefaultrrrrs  z Section.getcCs|D]}||||<qdS)zD A version of update that uses our ``__setitem__``. Nr)rHrrrrrrszSection.updatecCs8z ||}Wn ty,|tur$|}Yn0||=|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)rHrrrrrrpops   z Section.popcCs6|j|j}|std|d}||}||=||fS)zPops the first (key,val)z": 'popitem(): dictionary is empty'r)rrr)rHZsequencerrrrrpopitems 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) rclearrrrrr3rrrxrrrrs z Section.clearcCs2z ||WSty,|||<||YS0dS)z:A version of setdefault that sets sequence if appropriate.Nrrrrr setdefaults   zSection.setdefaultcCstt|j|jt|S)z8D.items() -> list of D's (key, value) pairs, as 2-tuples)rKziprrvaluesrxrrrrsz Section.itemscCs |j|jS)zD.keys() -> list of D's keysrrrxrrrkeyssz Section.keyscsfddjjDS)z D.values() -> list of D's valuescsg|] }|qSrrrrrxrrrrz"Section.values..rrxrrxrrszSection.valuescCstt|S)z=D.iteritems() -> an iterator over the (key, value) items of D)rPrKrrxrrr iteritemsszSection.iteritemscCst|j|jS)z.D.iterkeys() -> an iterator over the keys of D)rPrrrxrrriterkeysszSection.iterkeyscCstt|S)z2D.itervalues() -> an iterator over the values of D)rPrKrrxrrr itervaluesszSection.itervaluescs0fddddfddjjDS)zx.__repr__() <==> repr(x)cs.z |WSty(t|YS0dSrDr%rrrrxrr_getvals  z!Section.__repr__.._getvalz{%s}, cs$g|]}dt|t|fqSz%s: %sreprrrrrrsz$Section.__repr__..rrrrxrrrHr__repr__s  zSection.__repr__zx.__str__() <==> str(x)cCs\i}|D]N}||}t|tr(|}n&t|tr>> n = a.dict() >>> n == a 1 >>> n is a 0 )r_rrrKrV)rHZnewdictr this_entryrrrrs       z Section.dictcCsRt|D]@\}}||vrDt||trDt|trD|||q |||<q dS)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)rKrr_rmerge)rHrrrrrrrs z Section.mergecCs||jvr|j}n||jvr$|j}n td|||}||}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)rHZoldkeyZnewkeythe_listposrZcommZinline_commentrrrrename,s"          zSection.renameTc Ks i}tt|jD]d}|j|}z(|||fi|}|j|}|||<Wqtyt|r^n|j|}d||<Yq0qtt|jD]}|j|}|rz|||fi|Wn,ty|rĂn|j|}d||<Yn0|j|}||j|f||d|||<q|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)rangerr Exceptionrwalk) rHfunctionr/rZkeywargsoutrSrrrrrrJs@/          z Section.walkcCsn||}|dkrdS|dkr dSz*t|tjs6tn|jj|WSWntyhtd|Yn0dS)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)rHrrrrras_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' )intrrrras_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... )r]rrrras_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_rVrK)rHrresultrrras_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)rHrrrrrrs   zSection.restore_defaults)NN)F)N)N)TF)&r@rArBrurrrrrrrrrrrrrrrrrrrrr__iter__rr__str__rrrrrrrrrrrrrrrsJ  ;      U,rc@seZdZdZedejZedejZedejZ edejZ edejZ edZ edZ ed Zed 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 (?:(?|j rt|d}| dWdn1s0Yg}nt|t tfrt |}nt|tr,t|trfdd||n|D]}||||<q|`|dur"||nd|_dSt|dtturN|pJg}ntd|r||}|D]H}|rj|d d vrqjd D]}||r||_qqqqjtd d |DsJt|dd|D}|||jrBd|jdj}t|jdkr&d|} t | } n |jd} |j| _!|| _"| |`|durXd|_n ||dS)NrbzConfig file not found: "%s".wrncsB|jD]}||||<q|jD]}i||<||||qdSrDr)Z in_section this_sectionrr set_sectionrrrs   z$ConfigObj._load..set_sectionreadz>infile must be a filename, file like object, or list of lines.)  ) rrcss|]}t|tjVqdSrD)r_rrrrorrr rz"ConfigObj._load..cSsg|]}|dqS)r)rstriprrrrrrz#ConfigObj._load..z at line %s.rr9z2Parsing failed with several errors. First error %s)#r_rrfilenameospathisfileopen readlinesr2rwr1writerKrVrr!_errors_handle_configspecr3rerrr^ _handle_bomendswithnewlinesallr_parserprrerrorsZconfig) rHrr3hZcontentrrorinfor{errorrrrrsj   , (                zConfigObj._loadcCs|dur t}d|_g|_|d|_|d|_|d|_|d|_|d|_|d|_|d|_ |d|_ |d |_ d |_ d|_ |d |_|d |_g|_g|_d|_|jrd |_t|dS) Nr/r.r0r1r2r4r5rr6Fr8r7)r rr%r/r.r0r1r2r4r5rr6BOMr)r8r7initial_comment final_commentr3rrr)rHrrrrr0s.           zConfigObj._initialisecs0fddddfddjjDS)Ncs.z |WSty(t|YS0dSrDrrrxrrrQs  z#ConfigObj.__repr__.._getvalzConfigObj({%s})rcs$g|]}dt|t|fqSrrrrrrrWsz&ConfigObj.__repr__..rrxrrrrPs   zConfigObj.__repr__cCsP|jdur&|jtvr&|||jSt|ttfr>|d}n|}t|tjr\|||jS|jdur(t|j}|dkrtt D],\}\}}|sq| |r|||Sq|||jSt |}| |s|||jS|t |d}t|ttfr||d<n|}d|_|||jStt D]\}\}}t|tjr4| |s`q4n||_|sd|_|t |d}t|ttfr||d<n|}t|tjr|dSt|tjr|ddS||dS|||Sq4tjr"t|tr"||dSt|tjr@|ddS||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 Tr)rrr_decoder_rKrVrZ text_typeBOMSr startswithBOM_SETrr0 binary_type splitlinesdecodeZPY2str)rHrroencr0rZfinal_encodingnewlinerrrr'[s`          zConfigObj._handle_bomcCs&t|tjr|jr||jS|SdS)z@Decode ASCII strings to unicode if a self.encoding is specified.N)r_rr7rr9)rHZaStringrrr_a_to_us zConfigObj._a_to_ucCstt|tjr|dSt|tjr@|r6||dS|dS|rpt|D]"\}}t|tjrL||||<qL|S)z Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. T)r_rrr8r7r9 enumerate)rHrrrSrorrrr3s     zConfigObj._decodecCs&t|tjr|jr||jS|SdS)z'Decode element to unicode if necessary.N)r_rr7r6r9)rHrorrr_decode_elements zConfigObj._decode_elementcCst|tjst|S|SdS)zh Used by ``stringify`` within validate, to turn non-string values into strings. N)r_rrr:rHrNrrr_strs zConfigObj._strc Cs,|j}|jrd|_g}d}|}t|d}d}d}||kr|rDg}|d7}||} | } | rj| drzd}|| q2|s||_g}d}d}|j| } | dur| \} } }}}| r|j dur| |_ | d}|| dkr| d t ||q2||jkr@z|||j}Wn(ty<| d t ||Yq2Yn0n<||jkrT|j}n(||jdkrj|}n| d t ||q2||}||vr| d t||q2t||||d }|||<||j|<||j|<q2|j| } | dur| d| t||q2| \} }}| r$|j dur$| |_ |dddvrz|||||\}}}Wn(tyx| dt||Yq2Ynv0|jrd}z t|}WnZty}z@t|tkrd}nd}| |t||WYd}~q2WYd}~n d}~00n|jrdd}z t|}WnXty`}z>t|tr,d}nd}| |t||WYd}~q2WYd}~n d}~00n.zValue "%s" is not a string.""rrBrZrY#Value "%s" cannot be safely quoted.r)r8r_rKrVrr^rrrr4r:r^r0noquotr wspace_plus_get_single_quote_get_triple_quote)rHrNr]Zno_lists_no_quotesZ need_tripleZhash_triple_quoteZcheck_for_singlequotrrxrr^sH    "     zConfigObj._quotecCs4d|vrd|vrtd|nd|vr,t}nt}|S)NrZrYra)rsquotdquotrHrNrfrrrrd%s zConfigObj._get_single_quotecCsD|ddkr(|ddkr(td||ddkr.) rr0 _nolistvaluerrqrH _valueexprL _listvalueexpfindall)rHrNrTr0ZsingleZ empty_listrVrrrxrrQ9s6     zConfigObj._handle_valuec Cs|dd}|dd}|j|d}|j|d}||} | dur`t| } | || S||dkrtt||kr|d7}|d7}||} | |dkr|| 7}qtqqtt|| } | durt| \}} ||| |fS)z9Extract the value, where we are in a multiline situation.NrErr9rr) _triple_quoterrKrHrrjrq) rHrNrrSrRrfZnewvalueZ single_lineZ multi_linerTZretvalrorVrrrrOjs0        zConfigObj._multilinec Cst|ts~zt|dddd}Wn^tyN}ztd|WYd}~n8d}~0ty|}ztd|WYd}~n d}~00||_dS)zParse the configspec.T)r/r2rzParsing configspec failed: %sNzReading configspec failed: %s)r_r!rr rwr3)rHr3rWrrrr&s   "zConfigObj._handle_configspeccCs|j}|d}t|tr8|jD]}||vr |||_q |jD]p}|dkrLq>||vri||<d||_|r|j|g|j|<|j|d|j|<t||tr>||||_q>dS)z Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ __many__TrnN) r3rr_rrrrrr)rHrcopyr3manyrrrr_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%sFr\z = )r7r?r^rr=)rH indent_stringrrrVrrrr _write_lineszConfigObj._write_linecCs<d||d||j||dd|d|||fS)zWrite a section marker linervrCFr\rD)r=r^r?)rHrwrrrVrrr _write_markers   zConfigObj._write_markercCs.|sdS|j}|ds&||d7}||S)zDeal with a comment.rnrBz # )r5r5r=)rHrVrrrr_handle_comments  zConfigObj._handle_commentc sBjdurt_g}d}d}|dur~j}d_}jD]6}|}|}|rr||sr||}||qFj|j } |j |j D]} | |j vrq|j | D]6} | } | r| |s|| } || | q|| } |j| } t| tr8|| | j | | |j| dq|| | | | q|urjD]<}|}|}|r||s||}||q`|_|ur|Sjdur0|dur0jrfdd|D}jr,jdus tjdkr,|s|d t|d |d <|Sjp>> 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') NrBz# Frcsg|]}|jqSr)encoder)rlrxrrr/rz#ConfigObj.write..rrnrmoderwin32rrasciiwb).r5rr=r.r1r?rFr5rrrrrrlstriprzrr_rryextendr$rxr2rrr0rrrrr)rlineseprer}sysplatformrr(rr7r{r6rr")rHZoutfilerrcsZcspZint_valroZ stripped_linerwrZ comment_linerrVr<outputZ output_bytesr-rrxrr$s                   zConfigObj.writecs\durtjdurtdr0ddlm}|_rtjj_jj_jj_jj_jj _ jj _ j fdd}id}d}fdd j D} fd d j D} fd d j D} j D]} | d vrq| j vs| jvrVd} d}rb| j vrbj| gj| <j| d j| <n d} | }|| | || ||\}}qd}dj vrd}ndj vrd}|dur| D]$} | }|| ||d||\}}qg} | D]4} d}sd| <nd}d| }|| <q| D]4} d}s:d| <nd}d| }|| <q"j D]} urz| dkrzq^| jdur| | q^rƈj| gj| <j| d j| <j| d}|| <|dkrd}n|dkrd}nd}q^| _r$js$d}|rDrDrDt }|rNdS|rXdSS)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 sJj|dz|j|<Wnttjfy@Yn0zj|||d}WnPjy}z6rxt|jrd|<n ||<d}d}WYd}~nd}~00d}d|<j s|rj st|t t frfdd|D}n|r|durd}n  |}||ks|r||<sB|rB|j vrBj |||fS)N)missingFTcsg|]}|qSr)rA)ritemrxrrrrz>ConfigObj.validate..validate_entry..rn)rrZget_default_valuerrbaseErrorClasscheckr__vdtMissingValuer4rKrVrArr)rspecrrret_true ret_falserrWr3rsrpreserve_errorsrrH validatorrrvalidate_entrys<      z*ConfigObj.validate..validate_entryTcsg|]}|vr|qSrrrr)r3rrrrz&ConfigObj.validate..csg|]}|jvr|qSr)rrrrrrrcsg|]}|jvr|qSr)rrrrrrr)rr ___many___rnFrrrz"Value %r was provided as a sectionz)Section %r was provided as a single valuer)rrsr)r3rvalidaterrr1r2rr0r)r5rurrrrrrrrrranyr)rHrrrsrrrrrZ unvalidatedZincorrect_sectionsZincorrect_scalarsrrrrtr{rrrrrSs$         -                 zConfigObj.validatecCs ||d|_d|_dS)z@Clear ConfigObj instance and restore to 'freshly created' state.N)rrr3r rxrrrreset" szConfigObj.resetcCspt|jtjst|j}i}tD]}|dkr0q"t||||<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. r3N) r_rrrr'r rer rrr)rHrZcurrent_optionsrr3rrrreload- s zConfigObj.reload)NNNNTFTFFTNNFFF)N)T)NN)FFN)-r@rArBrurrrrMrGrnrormZ_single_line_singleZ_single_line_doubleZ_multi_line_singleZ_multi_line_doublerqrrrrrrr'r=r3r?rAr+rKrJrLr^rdrerQrOr&rurxryrzr$rrrrrrrr!/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|_dSrD)rrrxrrrrrS szSimpleVal.__init__FcCs|r ||S)z9A dummy check method, always returns the value unchanged.)r)rHrmemberrrrrrV szSimpleVal.checkN)F)r@rArBrurrrrrrrr"G s r"cCs|durg}g}|dkr t|S|dks2t|tr^||ddd|f|rV|t|St|D]X\}}|dkr|qjt||tr||t |||||qj||dd||fqj|r|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) sortedr_rrrrKrrrr*)ZcfgresZlevelsresultsrrrrrr*] 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+)Zconfrrr[rrrr+ s   r+)NN)r);rrrcodecsrrrrrZ_versionrr:r4rr6rrgrhrbrcrlrkobjectr__all__rrZMAX_INTERPOL_DEPTHr r?rr)rCZ_builderr7rqrrrrwr'rr r#r$r&r%r(r|rrrrrrr!r"r*r+rrrrs    7    | i" <