o
    3gTR                     @  s  d dl mZ d dlZd dlZd dlZd dlmZmZ d dl	m
Z
mZ d dlmZ d dlmZ d dlmZ eeZejejZZG dd	 d	eZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd dZ 										d;ddZ!dd  Z"G d!d" d"Z#G d#d$ d$e#Z$G d%d& d&e#Z%G d'd( d(Z&G d)d* d*eZ'G d+d, d,e'Z(G d-d. d.e'Z)e)e*d/d0Z+G d1d2 d2Z,e,d3d4 Z-e,d5d6 Z.e,d7d8 Z/e,d9d: Z0dS )<    )annotationsN)ABCabstractmethod)Callable	Generator)local)get_translation_for)getdocc                   @     e Zd ZdZdS )SwitchErrorzFA general switch related-error (base class of all other switch errors)N__name__
__module____qualname____doc__ r   r   L/home/garg/my-data/venv/lib/python3.10/site-packages/plumbum/cli/switches.pyr          r   c                   @  r
   )PositionalArgumentsErrorzDRaised when an invalid number of positional arguments has been givenNr   r   r   r   r   r      r   r   c                   @  r
   )SwitchCombinationErrorz=Raised when an invalid combination of switches has been givenNr   r   r   r   r   r      r   r   c                   @  r
   )UnknownSwitchz1Raised when an unrecognized switch has been givenNr   r   r   r   r   r      r   r   c                   @  r
   )MissingArgumentzCRaised when a switch requires an argument, but one was not providedNr   r   r   r   r   r   !   r   r   c                   @  r
   )MissingMandatorySwitchz1Raised when a mandatory switch has not been givenNr   r   r   r   r   r   %   r   r   c                   @  r
   )WrongArgumentTypezjRaised when a switch expected an argument of some type, but an argument of a wrong
    type has been givenNr   r   r   r   r   r   )   r   r   c                   @  r
   )SubcommandErrorz5Raised when there's something wrong with sub-commandsNr   r   r   r   r   r   .   r   r   c                   @  s   e Zd Zdd ZdS )
SwitchInfoc                 K  s"   |  D ]
\}}t| || qd S N)itemssetattr)selfkwargskvr   r   r   __init__6   s   zSwitchInfo.__init__N)r   r   r   r#   r   r   r   r   r   5   s    r   Fr   Switchesc                   s^   t trgdd D dd 
D 
dd D  	
fdd}|S )a  
    A decorator that exposes functions as command-line switches. Usage::

        class MyApp(Application):
            @switch(["-l", "--log-to-file"], argtype = str)
            def log_to_file(self, filename):
                handler = logging.FileHandler(filename)
                logger.addHandler(handler)

            @switch(["--verbose"], excludes=["--terse"], requires=["--log-to-file"])
            def set_debug(self):
                logger.setLevel(logging.DEBUG)

            @switch(["--terse"], excludes=["--verbose"], requires=["--log-to-file"])
            def set_terse(self):
                logger.setLevel(logging.WARNING)

    :param names: The name(s) under which the function is reachable; it can be a string
                  or a list of string, but at least one name is required. There's no need
                  to prefix the name with ``-`` or ``--`` (this is added automatically),
                  but it can be used for clarity. Single-letter names are prefixed by ``-``,
                  while longer names are prefixed by ``--``

    :param envname:   Name of environment variable to extract value from, as alternative to argv

    :param argtype: If this function takes an argument, you need to specify its type. The
                    default is ``None``, which means the function takes no argument. The type
                    is more of a "validator" than a real type; it can be any callable object
                    that raises a ``TypeError`` if the argument is invalid, or returns an
                    appropriate value on success. If the user provides an invalid value,
                    :func:`plumbum.cli.WrongArgumentType`

    :param argname: The name of the argument; if ``None``, the name will be inferred from the
                    function's signature

    :param list: Whether or not this switch can be repeated (e.g. ``gcc -I/lib -I/usr/lib``).
                 If ``False``, only a single occurrence of the switch is allowed; if ``True``,
                 it may be repeated indefinitely. The occurrences are collected into a list,
                 so the function is only called once with the collections. For instance,
                 for ``gcc -I/lib -I/usr/lib``, the function will be called with
                 ``["/lib", "/usr/lib"]``.

    :param mandatory: Whether or not this switch is mandatory; if a mandatory switch is not
                      given, :class:`MissingMandatorySwitch <plumbum.cli.MissingMandatorySwitch>`
                      is raised. The default is ``False``.

    :param requires: A list of switches that this switch depends on ("requires"). This means that
                     it's invalid to invoke this switch without also invoking the required ones.
                     In the example above, it's illegal to pass ``--verbose`` or ``--terse``
                     without also passing ``--log-to-file``. By default, this list is empty,
                     which means the switch has no prerequisites. If an invalid combination
                     is given, :class:`SwitchCombinationError <plumbum.cli.SwitchCombinationError>`
                     is raised.

                     Note that this list is made of the switch *names*; if a switch has more
                     than a single name, any of its names will do.

                     .. note::
                        There is no guarantee on the (topological) order in which the actual
                        switch functions will be invoked, as the dependency graph might contain
                        cycles.

    :param excludes: A list of switches that this switch forbids ("excludes"). This means that
                     it's invalid to invoke this switch if any of the excluded ones are given.
                     In the example above, it's illegal to pass ``--verbose`` along with
                     ``--terse``, as it will result in a contradiction. By default, this list
                     is empty, which means the switch has no prerequisites. If an invalid
                     combination is given, :class:`SwitchCombinationError
                     <plumbum.cli.SwitchCombinationError>` is raised.

                     Note that this list is made of the switch *names*; if a switch has more
                     than a single name, any of its names will do.

    :param help: The help message (description) for this switch; this description is used when
                 ``--help`` is given. If ``None``, the function's docstring will be used.

    :param overridable: Whether or not the names of this switch are overridable by other switches.
                        If ``False`` (the default), having another switch function with the same
                        name(s) will cause an exception. If ``True``, this is silently ignored.

    :param group: The switch's *group*; this is a string that is used to group related switches
                  together when ``--help`` is given. The default group is ``Switches``.

    :returns: The decorated function (with a ``_switch_info`` attribute)
    c                 S     g | ]}| d qS -lstrip.0nr   r   r   
<listcomp>       zswitch.<locals>.<listcomp>c                 S  r%   r&   r(   r*   r   r   r   r-      r.   c                 S  r%   r&   r(   r*   r   r   r   r-      r.   c                   s|    d u rt | j}t|dkr|d ntd}n }d u r#t| n}|s+t| }t| 	
||d| _| S )N      VALUE)namesenvnameargtypelistfunc	mandatoryoverridablegrouprequiresexcludesargnamehelp)	inspectgetfullargspecargslen_r	   strr   _switch_info)r6   argspecargname2help2r<   r4   r3   r;   r9   r=   r5   r7   r2   r8   r:   r   r   deco   s,   zswitch.<locals>.deco
isinstancerC   )r2   r4   r<   r5   r7   r:   r;   r=   r8   r9   r3   rI   r   rH   r   switch;   s   
b rL   c                    s    fdd}|S )zA decorator that exposes a function as a switch, "inferring" the name of the switch
    from the function's name (converting to lower-case, and replacing underscores with hyphens).
    The arguments are the same as for :func:`switch <plumbum.cli.switch>`.c                   s$   t | jddg R i | S )NrB   r'   )rL   r   replacer6   r@   r    r   r   rI      s   $zautoswitch.<locals>.decor   )r@   r    rI   r   rO   r   
autoswitch   s   rP   c                   @  sF   e Zd ZdZdZedZeddefddZdd	 Z	d
d Z
dd ZdS )
SwitchAttrab  
    A switch that stores its result in an attribute (descriptor). Usage::

        class MyApp(Application):
            logfile = SwitchAttr(["-f", "--log-file"], str)

            def main(self):
                if self.logfile:
                    open(self.logfile, "w")

    :param names: The switch names
    :param argtype: The switch argument's (and attribute's) type
    :param default: The attribute's default value (``None``)
    :param argname: The switch argument's name (default is ``"VALUE"``)
    :param kwargs: Any of the keyword arguments accepted by :func:`switch <plumbum.cli.switch>`
    __plumbum_switchattr_dict__r1   NFc           	      K  s   d| _ |r$|d ur$td|}d|v r|d  |7  < n|d|d< t|f|||d||  tg }|rU|d u rAg | _d S t|t|frO||| _d S |g| _d S || _d S )NzSets an attributez; the default is {0}r=   z; )r4   r<   r5   )	r   rB   formatr)   rL   type_default_valuerK   tuple)	r   r2   r4   defaultr5   r<   r    
defaultmsglisttyper   r   r   r#      s   


zSwitchAttr.__init__c                 C  s   |  || d S r   )__set__r   instvalr   r   r   __call__   s   zSwitchAttr.__call__c                 C  s$   |d u r| S t || ji | | jS r   )getattr	ATTR_NAMEgetrU   )r   r\   clsr   r   r   __get__  s   zSwitchAttr.__get__c                 C  sF   |d u rt dt|| jst|| j| |i d S |t|| j| < d S )Nz cannot set an unbound SwitchAttr)AttributeErrorhasattrr`   r   r_   r[   r   r   r   rZ     s
   zSwitchAttr.__set__)r   r   r   r   r`   rB   r1   rC   r#   r^   rc   rZ   r   r   r   r   rQ      s    
rQ   c                   @  "   e Zd ZdZdddZdd ZdS )	Flagab  A specialized :class:`SwitchAttr <plumbum.cli.SwitchAttr>` for boolean flags. If the flag is not
    given, the value of this attribute is ``default``; if it is given, the value changes
    to ``not default``. Usage::

        class MyApp(Application):
            verbose = Flag(["-v", "--verbose"], help = "If given, I'll be very talkative")

    :param names: The switch names
    :param default: The attribute's initial value (``False`` by default)
    :param kwargs: Any of the keyword arguments accepted by :func:`switch <plumbum.cli.switch>`,
                   except for ``list`` and ``argtype``.
    Fc                 K  s    t j| |fd |dd| d S )NFr4   rW   r5   )rQ   r#   r   r2   rW   r    r   r   r   r#      s   
zFlag.__init__c                 C  s   |  || j  d S r   )rZ   rU   )r   r\   r   r   r   r^   %     zFlag.__call__N)Fr   r   r   r   r#   r^   r   r   r   r   rg     s    
rg   c                   @  rf   )	CountOfaL  A specialized :class:`SwitchAttr <plumbum.cli.SwitchAttr>` that counts the number of
    occurrences of the switch in the command line. Usage::

        class MyApp(Application):
            verbosity = CountOf(["-v", "--verbose"], help = "The more, the merrier")

    If ``-v -v -vv`` is given in the command-line, it will result in ``verbosity = 4``.

    :param names: The switch names
    :param default: The default value (0)
    :param kwargs: Any of the keyword arguments accepted by :func:`switch <plumbum.cli.switch>`,
                   except for ``list`` and ``argtype``.
    r   c                 K  s&   t j| |fd |dd| || _d S )NTrh   )rQ   r#   rU   ri   r   r   r   r#   8  s   
zCountOf.__init__c                 C  s   |  |t| d S r   )rZ   rA   )r   r\   r"   r   r   r   r^   >  rj   zCountOf.__call__N)r   rk   r   r   r   r   rl   )  s    
rl   c                   @  s    e Zd ZdZdd Zdd ZdS )
positionalaY  
    Runs a validator on the main function for a class.
    This should be used like this::

        class MyApp(cli.Application):
            @cli.positional(cli.Range(1,10), cli.ExistingFile)
            def main(self, x, *f):
                # x is a range, f's are all ExistingFile's)

    Or, Python 3 only::

        class MyApp(cli.Application):
            def main(self, x : cli.Range(1,10), *f : cli.ExistingFile):
                # x is a range, f's are all ExistingFile's)


    If you do not want to validate on the annotations, use this decorator (
    even if empty) to override annotation validation.

    Validators should be callable, and should have a ``.choices()`` function with
    possible choices. (For future argument completion, for example)

    Default arguments do not go through the validator.

    #TODO: Check with MyPy

    c                 O     || _ || _d S r   )r@   kargs)r   r@   ro   r   r   r   r#   d     
zpositional.__init__c           	      C  s   t |}t|jdd  }d gt| }d }ttt|t| jD ]	}| j| ||< q#t|d t| jkr=| jd }| j D ]\}}||j	krN|}qB|||
|< qB||_||_|S )Nr0   )r>   r?   r5   r@   rA   rangeminro   r   varargsindexrm   positional_varargs)	r   functionm
args_namespositional_listrt   iitemvaluer   r   r   r^   h  s   


zpositional.__call__Nrk   r   r   r   r   rm   G  s    rm   c                   @  s.   e Zd ZdZedd Zd
ddZdd Zd	S )	Validatorr   c                 C  s   dS )z+Must be implemented for a Validator to workNr   r   objr   r   r   r^     s    zValidator.__call__ c                 C     t  S )zFShould return set of valid choices, can be given optional partial infosetr   partialr   r   r   choices  s   zValidator.choicesc                 C  sl   i }| j D ]}t|ddD ]}|d dkrt| |||< qqdd | D }d|}| jj d| d	S )
z/If not overridden, will print the slots as args	__slots__r   r   rB   c                 s  s"    | ]\}}| d | V  qdS )z = Nr   )r+   namer}   r   r   r   	<genexpr>  s     z%Validator.__repr__.<locals>.<genexpr>, ())__mro__r_   r   join	__class__r   )r   slotsrb   propmystrs
mystrs_strr   r   r   __repr__  s   

zValidator.__repr__Nr   )r   r   r   r   r   r^   r   r   r   r   r   r   r~     s    

r~   c                   @  s6   e Zd ZdZdZdd Zdd Zdd Zdd
dZdS )Rangea  
    A switch-type validator that checks for the inclusion of a value in a certain range.
    Usage::

        class MyApp(Application):
            age = SwitchAttr(["--age"], Range(18, 120))

    :param start: The minimal value
    :param end: The maximal value
    startendc                 C  rn   r   r   )r   r   r   r   r   r   r#     rp   zRange.__init__c                 C  s   d| j dd| jddS )N[dz..]r   r   r   r   r   r     s   zRange.__repr__c                 C  s8   t |}|| jk s|| jkrttd| j| j|S )NzNot in range [{0:d}..{1:d}])intr   r   
ValueErrorrB   rS   r   r   r   r   r^     s   zRange.__call__r   c                 C  s   t t| j| jd S )Nr0   )r   rr   r   r   r   r   r   r   r     s   zRange.choicesNr   )	r   r   r   r   r   r#   r   r^   r   r   r   r   r   r     s    r   c                   @  sR   e Zd ZdZdde dd ddZdd Z	d!d"ddZd!d#ddZd$ddZ	dS )%Seta  
    A switch-type validator that checks that the value is contained in a defined
    set of values. Usage::

        class MyApp(Application):
            mode = SwitchAttr(["--mode"], Set("TCP", "UDP", case_sensitive = False))
            num = SwitchAttr(["--num"], Set("MIN", "MAX", int, csv = True))

    :param values: The set of values (strings), or other callable validators, or types,
                   or any other object that can be compared to a string.
    :param case_sensitive: A keyword argument that indicates whether to use case-sensitive
                             comparison or not. The default is ``False``
    :param csv: splits the input as a comma-separated-value before validating and returning
                a list. Accepts ``True``, ``False``, or a string for the separator
    :param all_markers: When a user inputs any value from this set, all values are iterated
                        over. Something like {"*", "all"} would be a potential setting for
                        this option.
    F)case_sensitivecsvall_markersvaluesstr | Callable[[str], str]r   boolr   
bool | strr   collections.abc.Set[str]returnNonec                G  s6   || _ t|tr|rdnd| _n|| _|| _|| _d S )N,r   )r   rK   r   r   r   r   )r   r   r   r   r   r   r   r   r#     s   

zSet.__init__c                 C  s"   d dd | jD }d| dS )Nr   c                 s  s$    | ]}t |tr|n|jV  qd S r   )rK   rC   r   )r+   r"   r   r   r   r     s   " zSet.__repr__.<locals>.<genexpr>{})r   r   )r   r   r   r   r   r     s   zSet.__repr__Tr}   rC   	check_csvGenerator[str, None, None]c              	   c  s    | j r|r|| j D ]}| j| ddE d H  q| js"| }| jD ]5}t|tr@| js3| }||ks<|| j	v r?|V  q%t
t ||V  W d    n1 sUw   Y  q%d S )NF)r   )r   split
_call_iterstripr   lowerr   rK   rC   r   
contextlibsuppressr   )r   r}   r   r"   optr   r   r   r     s$   


zSet._call_iterstr | list[str]c                 C  sR   t | ||}|sd| d| j d}t|| jr|s#t|dkr%|S |d S )NzInvalid value: z (Expected one of r   r0   r   )r5   r   r   r   r   rA   )r   r}   r   r   msgr   r   r   r^     s   zSet.__call__r   c                   s4   dd | j D }|| jO } r fdd|D S |S )Nc                 S  s&   h | ]}t |tr|nd | dqS )r   r   rJ   r+   r   r   r   r   	<setcomp>  s   & zSet.choices.<locals>.<setcomp>c                   s   h | ]}|   r|qS r   )r   
startswithr   r   r   r   r     s    )r   r   )r   r   r   r   r   r   r     s
   
zSet.choicesN)
r   r   r   r   r   r   r   r   r   r   )T)r}   rC   r   r   r   r   )r}   rC   r   r   r   r   r   )
r   r   r   r   	frozensetr#   r   r   r^   r   r   r   r   r   r     s    	r   T)r   c                   @  s2   e Zd ZdZdd Zdd Zdd Zdd	d
ZdS )	Predicatez=A wrapper for a single-argument function with pretty printingc                 C  s
   || _ d S r   rN   )r   r6   r   r   r   r#        
zPredicate.__init__c                 C  s   | j jS r   )r6   r   r   r   r   r   __str__  s   zPredicate.__str__c                 C  s
   |  |S r   rN   )r   r]   r   r   r   r^     r   zPredicate.__call__r   c                 C  r   r   r   r   r   r   r   r     s   zPredicate.choicesNr   )r   r   r   r   r#   r   r^   r   r   r   r   r   r     s    r   c                 C  (   t | }| sttd| |S )zUA switch-type validator that ensures that the given argument is an existing directoryz{0} is not a directory)r   pathis_dirr   rB   rS   r]   pr   r   r   ExistingDirectory     
r   c                 C  s4   t | }| rt|  d| s|  |S )Nz1 is a file, should be nonexistent, or a directory)r   r   is_filer   existsmkdirr   r   r   r   MakeDirectory(  s   
r   c                 C  r   )zPA switch-type validator that ensures that the given argument is an existing filez{0} is not a file)r   r   r   r   rB   rS   r   r   r   r   ExistingFile2  r   r   c                 C  s(   t | }| rttd| |S )zRA switch-type validator that ensures that the given argument is a nonexistent pathz{0} already exists)r   r   r   r   rB   rS   r   r   r   r   NonexistentPath;  r   r   )
NNFFr   r   NFr$   N)1
__future__r   collections.abccollectionsr   r>   abcr   r   typingr   r   plumbumr   plumbum.cli.i18nr   plumbum.libr	   r   _translationgettextngettextrB   	Exceptionr   r   r   r   r   r   r   r   r   rL   rP   rQ   rg   rl   rm   r~   r   r   rC   CSVr   r   r   r   r   r   r   r   r   <module>   sd    
 E:"L

	
