U
    e1                  	   @   s   d Z ddlZddlZddlZddlmZ ddlmZmZ ddl	m
Z
 ddlmZmZmZmZmZ ddlmZmZ ddlmZ d	d
ddddgZG dd	 d	ejZddddejejdddf	dd
Zdd ZdddZdd Zdd ZG dd de Z!dS )z
Dispatching
~~~~~~~~~~~
    N)GeneratorType)add_commandsset_default_command)autocomplete)ATTR_EXPECTS_NAMESPACE_OBJECTATTR_WRAPPED_EXCEPTIONS!ATTR_WRAPPED_EXCEPTIONS_PROCESSORDEST_FUNCTIONPARSER_FORMATTER)CommandErrorDispatchingError)get_arg_specArghNamespacedispatchdispatch_commanddispatch_commandsr
   
EntryPointc                       s4   e Zd ZdZ fddZ fddZdd Z  ZS )r   zC
    A namespace object which collects the stack of functions.
    c                    s   t t| j|| g | _d S N)superr   __init___functions_stack)selfargskwargs	__class__ o/mounts/lovelace/software/anaconda3/envs/qiime2-amplicon-2023.9/lib/python3.8/site-packages/argh/dispatching.pyr   .   s    zArghNamespace.__init__c                    s,   |t kr| j| ntt| || d S r   )r	   r   appendr   r   __setattr__)r   kvr   r   r   r   2   s    	zArghNamespace.__setattr__c                 C   s
   | j d S )N)r   )r   r   r   r   get_function@   s    zArghNamespace.get_function)__name__
__module____qualname____doc__r   r   r#   __classcell__r   r   r   r   r   )   s   TFc
                 C   s  |rt |  |dkr"tjdd }|rJ|rJ|d dkrJ|d |d |sTt }|	rr| j||d\}
}||
_n| j||d}
t	|
}|rt
||
||d}n
|  g}|dkrt }n|}|D ] }|t| |s|d q|dkr|d | S dS )	a  
    Parses given list of arguments using given parser, calls the relevant
    function and prints the result.

    The target function should expect one positional argument: the
    :class:`argparse.Namespace` object.

    :param parser:

        the ArgumentParser instance.

    :param argv:

        a list of strings representing the arguments. If `None`, ``sys.argv``
        is used instead. Default is `None`.

    :param add_help_command:

        if `True`, converts first positional argument "help" to a keyword
        argument so that ``help foo`` becomes ``foo --help`` and displays usage
        information for "foo". Default is `True`.

    :param output_file:

        A file-like object for output. If `None`, the resulting lines are
        collected and returned as a string. Default is ``sys.stdout``.

    :param errors_file:

        Same as `output_file` but for ``sys.stderr``.

    :param raw_output:

        If `True`, results are written to the output file raw, without adding
        whitespaces or newlines between yielded strings. Default is `False`.

    :param completion:

        If `True`, shell tab completion is enabled. Default is `True`. (You
        will also need to install it.)  See :mod:`argh.completion`.

    :param skip_unknown_args:

        If `True`, unknown arguments do not cause an error
        (`ArgumentParser.parse_known_args` is used).

    :param namespace:

        An `argparse.Namespace`-like object.  By default an
        :class:`argh.dispatching.ArghNamespace` object is used.  Please note
        that support for combined default and nested functions may be broken
        if a different type of object is forced.

    By default the exceptions are not wrapped and will propagate. The only
    exception that is always wrapped is :class:`~argh.exceptions.CommandError`
    which is interpreted as an expected event so the traceback is hidden.
    You can also mark arbitrary exceptions as "wrappable" by using the
    :func:`~argh.decorators.wrap_errors` decorator.
    N   r   helpz--help)	namespace)pre_call
)r   sysargvpopr   r   parse_known_argsZ_unknown_args
parse_args _get_function_from_namespace_obj_execute_commandformat_usageioStringIOwritestrseekread)parserr/   Zadd_help_command
completionr,   Zoutput_fileerrors_file
raw_outputr+   Zskip_unknown_argsnamespace_objZunknown_argsfunctionlinesfliner   r   r   r   D   sB    G

   


c              	   C   sb   t | tr4z|  }W qL ttfk
r0   Y d S X nt| tsBd S t| t}|rZt|ds^d S |S )N__call__)
isinstancer   r#   AttributeError
IndexErrorhasattrr	   getattr)r@   rA   r   r   r   r3      s    



r3   c           
   
   #   s   |r|  fdd}t g}|t tg 7 }z| }|D ]
}|V  q<W nR t|k
r } z0t tdd }	|t|	| |d W 5 d}~X Y nX dS )a  
    Assumes that `function` is a callable.  Tries different approaches
    to call it (with `namespace_obj` or with ordinary signature).
    Yields the results line by line.

    If :class:`~argh.exceptions.CommandError` is raised, its message is
    appended to the results (i.e. yielded by the generator as a string).
    All other exceptions propagate unless marked as wrappable
    by :func:`wrap_errors`.
    c            	      3   s4  t tdr} ndd  t fddt D t}fdd|jD }t |dg }tfd	d|D }|jr|t |j7 }t |d
t |dg }|rtg|j |jg | }tD ]&}|	ds||krqt |||< qȈ||} t
| tttfr | D ]}|V  qn| d k	r0| V  d S )NFc                 S   s   |  ddS )N-_)replace)keyr   r   r   	_flat_key   s    z2_execute_command.<locals>._call.<locals>._flat_keyc                 3   s   | ]\}} ||fV  qd S r   r   ).0r    r!   )rO   r   r   	<genexpr>   s     z2_execute_command.<locals>._call.<locals>.<genexpr>c                    s   g | ]} | qS r   r   rP   r    	all_inputr   r   
<listcomp>   s     z3_execute_command.<locals>._call.<locals>.<listcomp>
kwonlyargsc                 3   s   | ]}| | fV  qd S r   r   rR   rS   r   r   rQ     s     varkwkeywordsrL   )rJ   r   dictvarsitemsr   r   varargsr	   
startswithrF   r   listtuple)	resultspec
positionalkwonlyrX   rW   Z
not_kwargsr    rD   rA   r@   )rO   rT   r   _call   s.    


z_execute_command.<locals>._callc                 S   s
   d | S )Nz{0.__class__.__name__}: {0})format)er   r   r   <lambda>(      z"_execute_command.<locals>.<lambda>r-   N)r   rJ   r   r_   r   r8   r9   )
rA   r@   r>   r,   re   Zwrappable_exceptionsr`   rD   rg   	processorr   rd   r   r4      s"    -r4   c                 O   s*   t jtd}t||  t|f|| dS )a  
    A wrapper for :func:`dispatch` that creates a one-command parser.
    Uses :attr:`argh.constants.PARSER_FORMATTER`.

    This::

        dispatch_command(foo)

    ...is a shortcut for::

        parser = ArgumentParser()
        set_default_command(parser, foo)
        dispatch(parser)

    This function can be also used as a decorator::

        @dispatch_command
        def main(foo=123):
            return foo + 1

    formatter_classN)argparseArgumentParserr
   r   r   )rA   r   r   r<   r   r   r   r   /  s    
c                 O   s*   t jtd}t||  t|f|| dS )aL  
    A wrapper for :func:`dispatch` that creates a parser, adds commands to
    the parser and dispatches them.
    Uses :attr:`PARSER_FORMATTER`.

    This::

        dispatch_commands([foo, bar])

    ...is a shortcut for::

        parser = ArgumentParser()
        add_commands(parser, [foo, bar])
        dispatch(parser)

    rk   N)rm   rn   r
   r   r   )Z	functionsr   r   r<   r   r   r   r   J  s    
c                   @   s4   e Zd ZdZdddZdddZdd Zd	d
 ZdS )r   ap  
    An object to which functions can be attached and then dispatched.

    When called with an argument, the argument (a function) is registered
    at this entry point as a command.

    When called without an argument, dispatching is triggered with all
    previously registered commands.

    Usage::

        from argh import EntryPoint

        app = EntryPoint('main', dict(description='This is a cool app'))

        @app
        def ls():
            for i in range(10):
                print i

        @app
        def greet():
            print 'hello'

        if __name__ == '__main__':
            app()

    Nc                 C   s   |pd| _ g | _|pi | _d S )NZunnamed)namecommandsparser_kwargs)r   ro   rq   r   r   r   r   ~  s    
zEntryPoint.__init__c                 C   s   |r|  | |S |  S r   )_register_command	_dispatchr   rC   r   r   r   rE     s    
zEntryPoint.__call__c                 C   s   | j | d S r   )rp   r   rt   r   r   r   rr     s    zEntryPoint._register_commandc                 C   s<   | j std| jtjf | j}t|| j  t| d S )Nz!no commands for entry point "{0}")	rp   r   rf   ro   rm   rn   rq   r   r   )r   r<   r   r   r   rs     s    
zEntryPoint._dispatch)NN)N)r$   r%   r&   r'   r   rE   rr   rs   r   r   r   r   r   `  s
   

)N)"r'   rm   r6   r.   typesr   Zargh.assemblingr   r   Zargh.completionr   Zargh.constantsr   r   r   r	   r
   Zargh.exceptionsr   r   Z
argh.utilsr   __all__	Namespacer   stdoutstderrr   r3   r4   r   r   objectr   r   r   r   r   <module>
   s@   

~
Y