
    )g:                        S r SSKrSSKrSSKrSSKrSSKrSSKJr  SSKJ	r	  SSK
Jr  SSKJr  SSKJrJrJrJrJrJrJrJrJr   \(       a  SSKJr  SS	KJr  \\\   \\   \\4   r\R<                  " S
5      r\R@                  " S5      r! " S S5      r"\RF                  S:  d  \(       a    " S S\RH                  \   \\\4   \5      r%O " S S\RL                  \   \\5      r% " S S\%S   5      r'g! \ a     Nf = f)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 substvars files is
defined in `deb-substvars(5)
<https://manpages.debian.org/unstable/dpkg-dev/deb-substvars.5.html>`_

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)	DictSetOptionalUnionIteratorIOIterableTYPE_CHECKINGType)Self)PathLikeTzB^(?P<name>\w[-:\dA-Za-z]*)(?P<assignment_type>[?]?=)(?P<value>.*)$c                       \ rS rSrSS/r  SS jr\S\4S j5       r\R                  S 5       rS r
S\4S	 jrS
 rSrg)Substvar?   _assignment_operator_valuec                     Xl         X l        g N)r   assignment_operator)selfinitial_valuer   s      2/usr/lib/python3/dist-packages/debian/substvars.py__init__Substvar.__init__C   s     $#6     returnc                     U R                   $ r   )r   r   s    r   r   Substvar.assignment_operatorT   s    (((r    c                 8    US;  a  [        SU-   5      eXl        g )N>   =?=z-Operator must be one of: "=", or "?=" - got: )
ValueErrorr   )r   new_operators     r   r   r$   X   s#     {*L|[\\$0!r    c                 0   U R                   S:X  a	  U1U l         g [        U R                   [        5      (       a>  U R                   R                  S5       Vs1 s H  o"R	                  5       iM     snU l         U R                   R                  U5        g s  snf )N ,)r   
isinstancestrsplitstripadd)r   dependency_clausevs      r   add_dependencySubstvar.add_dependency_   sn    ;;",-DKdkk3''.2kk.?.?.DE.D779.DEDK)* Fs   Bc                     [        U R                  [        5      (       a$  SR                  [	        U R                  5      5      $ U R                  $ )Nz, )r-   r   setjoinsortedr#   s    r   resolveSubstvar.resolvei   s5    dkk3''99VDKK011{{r    c                     Ub  [        U[        5      (       d  gU R                  UR                  :w  a  gU R                  5       UR                  5       :H  $ NF)r-   r   r   r:   r   others     r   __eq__Substvar.__eq__n   sD    =
5( ; ;##u'@'@@||~00r    )r   r   r   N)r+   r&   )__name__
__module____qualname____firstlineno__	__slots__r   propertyr.   r   setterr4   r:   r@   __static_attributes__ r    r   r   r   ?   sb    '2I%'%(7" )S ) ) 1  1+ 
1r    r   )   	   c                       \ rS rSrSrg)_Substvars_Basex   rJ   N)rB   rC   rD   rE   rI   rJ   r    r   rN   rN   x   s    r    rN   c                        \ rS rSrS rS rSrg)rN      c                     U $ r   rJ   r#   s    r   	__enter___Substvars_Base.__enter__   s    Kr    c                     g r   rJ   )r   exc_typeexc_valexc_tbs       r   __exit___Substvars_Base.__exit__   s    r    rJ   N)rB   rC   rD   rE   rS   rY   rI   rJ   r    r   rN   rN      s    		r    c                   &  ^  \ rS rSrSrSS/rSS jr\SS j5       r\	S 5       r
\
R                  S	 5       r
\	S
 5       r\R                  S 5       rS rU 4S jrS rS\4S jrS rS rS rS r\	S 5       rS rS\4S jrSS jrS rS rSrU =r$ )	Substvars   aO  Substvars 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_pathr!   c                 0    [        5       U l        S U l        g r   )r   r^   r_   r#   s    r   r   Substvars.__init__   s    %-#r    c                    U " 5       n [        USSS9 nUR                  U5        SSS5        Xl        U$ ! , (       d  f       N= f! [         a0  nUR                  [        R                  :w  d  U(       d  e  SnANNSnAff = f)ar  Shorthand 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.
rutf-8encodingN)openread_substvarsOSErrorerrnoENOENTsubstvars_path)clsrl   
missing_ok	substvarsfdes         r   load_from_pathSubstvars.load_from_path   sq    6 E		ncG<((, =
 $2  =< 	ww%,,&j /9	s1   A 6A 
A A A 
B&A<<Bc                     U R                   $ r   r^   r#   s    r   _varsSubstvars._vars   s     r    c                     Xl         g r   ru   )r   	vars_dicts     r   rv   rw      s	     $r    c                     U R                   $ r   r_   r#   s    r   rl   Substvars.substvars_path   s     ###r    c                     Xl         g r   r{   )r   new_paths     r   rl   r|      s
      (r    c                      U R                   U   nUR                  U5        g! [         a    [        5       nX0R                   U'    N6f = f)ac  Add 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)rv   KeyErrorr   r4   )r   substvarr2   variables       r   r4   Substvars.add_dependency   sJ    ,	,zz(+H 	 12  	,zH#+JJx 	,s   # "AAc                 J   > Uc  U R                  5         [        TU ]	  XU5      $ r   )savesuperrY   )r   rV   rW   rX   	__class__s       r   rY   Substvars.__exit__  s&     IIKw6::r    c                 ,    [        U R                  5      $ r   )iterrv   r#   s    r   __iter__Substvars.__iter__  s    DJJr    c                 ,    [        U R                  5      $ r   )lenr^   r#   s    r   __len__Substvars.__len__  s    4??##r    c                     XR                   ;   $ r   rv   )r   items     r   __contains__Substvars.__contains__  s    zz!!r    c                 <    U R                   U   R                  5       $ r   )rv   r:   r   keys     r   __getitem__Substvars.__getitem__  s    zz#&&((r    c                     U R                   U	 g r   r   r   s     r   __delitem__Substvars.__delitem__  s    JJsOr    c                 4    [        U5      U R                  U'   g r   )r   rv   )r   r   values      r   __setitem__Substvars.__setitem__#  s    "5/

3r    c                     U R                   $ )a  Provides 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
r   r#   s    r   as_substvarSubstvars.as_substvar'  s    6 zzr    c                 f    Ub  [        U[        5      (       d  gU R                  UR                  :H  $ r=   )r-   r\   rv   r>   s     r   r@   Substvars.__eq__D  s)    =
5) < <zzU[[((r    c                 b    SR                  S U R                  R                  5        5       5      $ )zDebug aid that generates a string representation of the content

For persisting the contents, please consider `save()` or `write_substvars`.
r+   c              3   z   #    U  H1  u  pS R                  XR                  UR                  5       5      v   M3     g7fz{}{}{}
Nformatr   r:   .0kr3   s      r   	<genexpr>!Substvars.dump.<locals>.<genexpr>O  s5      #541 "((,A,A199;OO#5   9;)r8   rv   itemsr#   s    r   dumpSubstvars.dumpJ  s/    
 ww #'::#3#3#5  	r    c                     U R                   c  [        S5      e[        U R                   SSS9 nU R                  U5      sSSS5        $ ! , (       d  f       g= f)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_substvarswrd   re   )r_   	TypeErrorrg   write_substvars)r   rp   s     r   r   Substvars.saveS  sU     ' O P P $&&g>"''+ ?>>s   A		
Ac                 d    UR                  S U R                  R                  5        5       5        g)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)
c              3   z   #    U  H1  u  pS R                  XR                  UR                  5       5      v   M3     g7fr   r   r   s      r   r   ,Substvars.write_substvars.<locals>.<genexpr>g  s5      '9tq &,,Q0E0Eqyy{SS'9r   N)
writelinesrv   r   )r   fileobjs     r   r   Substvars.write_substvarsa  s,     	 '+zz'7'7'9 	r    c                 
   [        5       nU Hm  nUR                  5       S:X  d	  US   S:X  a  M"  [        R                  UR	                  S5      5      nU(       d  MO  UR                  5       u  pVn[        XvS9X%'   Mo     X l        g)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.
r+   r   #z
)r   N)r   r0   _SUBSTVAR_PATTERNmatchrstripgroupsr   rv   )r   r   ry   linemvarnamer   r   s           r   rh   Substvars.read_substvarsk  ss    0  M	Dzz|r!T!W^!''F(;<A23((*/G%!)%!YI  
r    )r_   rv   r^   )r!   N)F)rB   rC   rD   rE   __doc__rF   r   classmethodrr   rG   rv   rH   rl   r4   rY   r   intr   r   r   r   r   r   r@   r.   r   r   r   rh   rI   __classcell__)r   s   @r   r\   r\      s    > 01I$ " "H  
 \\$ $
 $ $ ( (3:; $ $")*  8)c ,! !r    r\   )(r   
contextlibrj   resystypingabcr   collectionsr   collections.abcr   typesr   r   r   r	   r
   r   r   r   r   r   r   osr   r.   bytesAnyPathImportErrorTypeVarr   compiler   r   version_infoAbstractContextManagerrN   Genericr\   rJ   r    r   <module>r      s   !H   	 
   # *  Z Z Z	xUBC NN3JJI 
51 51p v*;;A>sTWx@XZ] &..+^S D, Dg  		s   "C6 6C?>C?