)uyc#:dZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z ddlmZmZmZmZmZmZmZmZmZ ddlmZeeeefZn #e$rYnwxYwejd Zejd Z Gd d Z!ej"d kser$Gddej#ee eefeZ$nGddej%ee eZ$Gdde$dZ&dS)a Facilities for reading and writing Debian substvars files The aim of this module is to provide programmatic access to Debian substvars files to query and manipulate them. The format for the changelog is defined in `deb-substvars(5) `_ Overview ======== The most common use-case for substvars is for package helpers to add or update a substvars (e.g., to add a dependency). This would look something like: >>> from debian.substvars import Substvars >>> from tempfile import TemporaryDirectory >>> import os >>> # Using a tmp dir for the sake of doctests >>> with TemporaryDirectory() as debian_dir: ... filename = os.path.join(debian_dir, "foo.substvars") ... with Substvars.load_from_path(filename, missing_ok=True) as svars: ... svars.add_dependency("misc:Depends", "bar (>= 1.0)") By default, the module creates new substvars as "mandatory" substvars (that triggers a warning by dpkg-gecontrol if not used. However, it does also support the "optional" substvars introduced in dpkg 1.21.8. See `Substvars.as_substvars` for an example of how to use the "optional" substvars. The :class:`Substvars` class is the key class within this module. Substvars Classes ----------------- N)ABC) OrderedDict)MutableMapping) TracebackType) DictSetOptionalUnionIteratorIOIterable TYPE_CHECKINGType)PathLikeTzB^(?P\w[-:\dA-Za-z]*)(?P[?]?=)(?P.*)$cjeZdZddgZ d dZedZejdZdZd Z d Z d S) Substvar_assignment_operator_value=c"||_||_dSN)rassignment_operator)self initial_valuers 2/usr/lib/python3/dist-packages/debian/substvars.py__init__zSubstvar.__init__As$ #6   c|jSr)rrs rrzSubstvar.assignment_operatorRs ((rc@|dvrtd|z||_dS)N>?=rz-Operator must be one of: "=", or "?=" - got: ) ValueErrorr)r new_operators rrzSubstvar.assignment_operatorWs1 { * *L|[\\ \$0!!!rc|jdkr |h|_dSt|jtr)d|jdD|_|j|dS)Nrc6h|]}|S)strip).0vs r z*Substvar.add_dependency..es EEE17799EEEr,)r isinstancestrsplitadd)rdependency_clauses radd_dependencyzSubstvar.add_dependency^ss ;"  ,-DK F dk3 ' ' FEEdk.?.?.D.DEEEDK )*****rct|jtr'dt |jS|jS)Nz, )r.rsetjoinsortedr!s rresolvezSubstvar.resolvehs: dk3 ' ' 299VDK0011 1{rc|t|tsdS|j|jkrdS||kSNF)r.rrr8rothers r__eq__zSubstvar.__eq__nsK = 5( ; ;=5  #u'@ @ @5||~~00rN)rr) __name__ __module__ __qualname__ __slots__rpropertyrsetterr3r8r=r(rrrr=s'2I%'%(7777"))X)11 1 +++ 11111rr) ceZdZdS)_Substvars_BaseN)r>r?r@r(rrrGrGxs rrGceZdZdZdZdS)rGc|Srr(r!s r __enter__z_Substvars_Base.__enter__sKrcdSrr()rexc_typeexc_valexc_tbs r__exit__z_Substvars_Base.__exit__s4rN)r>r?r@rJrOr(rrrGrGs2        rceZdZdZddgZdZeddZedZ e j dZ ed Z e j d Z d Z fd Z d ZdefdZdZdZdZdZedZdZdZdZdZdZxZS) SubstvarsaSubstvars is a dict-like object containing known substvars for a given package. >>> substvars = Substvars() >>> substvars['foo'] = 'bar, golf' >>> substvars['foo'] 'bar, golf' >>> substvars.add_dependency('foo', 'dpkg (>= 1.20.0)') >>> substvars['foo'] 'bar, dpkg (>= 1.20.0), golf' >>> 'foo' in substvars True >>> sorted(substvars) ['foo'] >>> del substvars['foo'] >>> substvars['foo'] Traceback (most recent call last): ... KeyError: 'foo' >>> substvars.get('foo') >>> # None >>> substvars['foo'] = "" >>> substvars['foo'] '' The Substvars object also provide methods for serializing and deserializing the substvars into and from the format used by dpkg-gencontrol. The Substvars object can be used as a context manager, which causes the substvars to be saved when the context manager exits successfully (i.e., no exceptions are raised). _vars_dict_substvars_pathc:t|_d|_dSr)rrRrSr!s rrzSubstvars.__init__s%--#rFc|} t|dd5}||dddn #1swxYwYn/#t$r"}|jtjks|sYd}~nd}~wwxYw||_|S)aShorthand for initializing a Substvars from a file The return substvars will have `substvars_path` set to the provided path enabling `save()` to work out of the box. This also makes it easy to combine this with the context manager interface to automatically save the file again. >>> import os >>> from tempfile import TemporaryDirectory >>> with TemporaryDirectory() as tmpdir: ... filename = os.path.join(tmpdir, "foo.substvars") ... # Obviously, this does not exist ... print("Exists before: " + str(os.path.exists(filename))) ... with Substvars.load_from_path(filename, missing_ok=True) as svars: ... svars.add_dependency("misc:Depends", "bar (>= 1.0)") ... print("Exists after: " + str(os.path.exists(filename))) Exists before: False Exists after: True :param substvars_path: The path to load from :param missing_ok: If True, then the path does not have to exist (i.e. FileNotFoundError causes an empty Substvars object to be returned). Combined with the context manager, this is useful for packaging helpers that want to append / update to the existing if it exists or create it if it does not exist. rutf-8encodingN)openread_substvarsOSErrorerrnoENOENTsubstvars_path)clsr_ missing_ok substvarsfdes rload_from_pathzSubstvars.load_from_paths6CEE  ncG<<< -((,,, - - - - - - - - - - - - - - -   w%,&&j&'&&&& $2  s9A A A AA AA A8A33A8c|jSrrRr!s r_varszSubstvars._varss rc||_dSrrg)r vars_dicts rrhzSubstvars._varss$rc|jSrrSr!s rr_zSubstvars.substvars_paths ##rc||_dSrrl)rnew_paths rr_zSubstvars.substvars_paths (rc |j|}n(#t$rt}||j|<YnwxYw||dS)aAdd a dependency clause to a given substvar >>> substvars = Substvars() >>> # add_dependency automatically creates variables >>> 'misc:Recommends' not in substvars True >>> substvars.add_dependency('misc:Recommends', "foo (>= 1.0)") >>> substvars['misc:Recommends'] 'foo (>= 1.0)' >>> # It can be appended to other variables >>> substvars['foo'] = 'bar, golf' >>> substvars.add_dependency('foo', 'dpkg (>= 1.20.0)') >>> substvars['foo'] 'bar, dpkg (>= 1.20.0), golf' >>> # Exact duplicates are ignored >>> substvars.add_dependency('foo', 'dpkg (>= 1.20.0)') >>> substvars['foo'] 'bar, dpkg (>= 1.20.0), golf' N)rhKeyErrorrr3)rsubstvarr2variables rr3zSubstvars.add_dependencysh, ,z(+HH , , ,zzH#+DJx  ,  122222s "55cv||t|||Sr)savesuperrO)rrLrMrN __class__s rrOzSubstvars.__exit__s4   IIKKKww'6:::rc*t|jSr)iterrhr!s r__iter__zSubstvars.__iter__sDJrreturnc*t|jSr)lenrRr!s r__len__zSubstvars.__len__s4?###rc||jvSrrh)ritems r __contains__zSubstvars.__contains__stz!!rc@|j|Sr)rhr8rkeys r __getitem__zSubstvars.__getitem__sz#&&(((rc|j|=dSrrrs r __delitem__zSubstvars.__delitem__ s JsOOOrc4t||j|<dSr)rrh)rrvalues r __setitem__zSubstvars.__setitem__$s"5// 3rc|jS)aProvides a mapping to the Substvars object for more advanced operations Treating a substvars file mostly as a "str -> str" mapping is sufficient for many cases. But when full control over the substvars (like fiddling with the assignment operator) is needed this attribute is useful. >>> content = ''' ... # Some comment (which is allowed but no one uses them - also, they are not preserved) ... shlib:Depends=foo (>= 1.0), libbar2 (>= 2.1-3~) ... random:substvar?=With the new assignment operator from dpkg 1.21.8 ... ''' >>> substvars = Substvars() >>> substvars.read_substvars(content.splitlines()) >>> substvars.as_substvar["shlib:Depends"].assignment_operator '=' >>> substvars.as_substvar["random:substvar"].assignment_operator '?=' >>> # Mutation is also possible >>> substvars.as_substvar["shlib:Depends"].assignment_operator = '?=' >>> print(substvars.dump(), end="") shlib:Depends?=foo (>= 1.0), libbar2 (>= 2.1-3~) random:substvar?=With the new assignment operator from dpkg 1.21.8 rr!s r as_substvarzSubstvars.as_substvar(s 6zrcT|t|tsdS|j|jkSr:)r.rQrhr;s rr=zSubstvars.__eq__Es) = 5) < <=5zU[((rcndd|jDS)zDebug aid that generates a string representation of the content For persisting the contents, please consider `save()` or `write_substvars`. rc3xK|]5\}}d||j|V6dSz{}{}{} Nformatrr8r*kr+s r z!Substvars.dump..QsW1a"((A,A199;;OOr)r6rhitemsr!s rdumpzSubstvars.dumpKsD ww#':#3#3#5#5 rc|jtdt|jdd5}||cdddS#1swxYwYdS)zSave the substvars file Replace the path denoted by the `substvars_path` attribute with the in-memory version of the substvars. Note that the `substvars_path` property must be not None for this method to work. NzcThe substvar does not have a substvars_path: Please set substvars_path first or use write_substvarswrWrX)rS TypeErrorrZwrite_substvars)rrcs rrtzSubstvars.saveUs   'OPP P$&g > > > ,"''++ , , , , , , , , , , , , , , , , , ,sAAAcr|d|jDdS)zWrite a copy of the substvars to an open text file :param fileobj: The open file (should open in text mode using the UTF-8 encoding) c3xK|]5\}}d||j|V6dSrrrs rrz,Substvars.write_substvars..jsW#q!&,,Q0Eqyy{{SSrN) writelinesrhr)rfileobjs rrzSubstvars.write_substvarsdsP '+z'7'7'9'9     rc<t}|D]}|dks |ddkr't|d}|sW|\}}}t ||||<||_dS)a Read substvars from an open text file in the format supported by dpkg-gencontrol On success, all existing variables will be discarded and only variables from the file will be present after this method completes. In case of any IO related errors, the object retains its state prior to the call of this method. >>> content = ''' ... # Some comment (which is allowed but no one uses them - also, they are not preserved) ... shlib:Depends=foo (>= 1.0), libbar2 (>= 2.1-3~) ... random:substvar?=With the new assignment operator from dpkg 1.21.8 ... ''' >>> substvars = Substvars() >>> substvars.read_substvars(content.splitlines()) >>> substvars["shlib:Depends"] 'foo (>= 1.0), libbar2 (>= 2.1-3~)' >>> substvars["random:substvar"] 'With the new assignment operator from dpkg 1.21.8' :param fileobj: An open file (in text mode using the UTF-8 encoding) or an iterable of str that provides line by line content. rr#z )rN)rr)_SUBSTVAR_PATTERNmatchrstripgroupsrrh)rrrjlinemvarnamerrs rr[zSubstvars.read_substvarsns0 MM  Z ZDzz||r!!T!W^^!'' F(;(;<r?r@__doc__rAr classmethodrerBrhrCr_r3rOryintr}rrrrrr=rrtrr[ __classcell__)rvs@rrQrQs>01I$$$ """["HX  \$$\$ $$X$(((333:;;;;;   $$$$$""")))***X8)))  , , ,!!!!!!!rrQ)'r contextlibr]resystypingabcr collectionsrcollections.abcrtypesrrrr r r r r rrosrr/bytesAnyPath ImportErrorTypeVarrcompilerr version_infoAbstractContextManagerrGGenericrQr(rrrs<!!H ######******ZZZZZZZZZZZZZZZZZZZZZZ Hc5()GG   D FN3BJI 7171717171717171tv     *;A>sTWx@XZ]    &.+^SGGGGG ,GGGGGsAA A