o
    ThZ                     @   s~   d dl Z d dlmZ d dlmZmZmZmZmZm	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 G d	d
 d
ZdS )    N)
ModuleType)AnyCallableDictListOptionalTuple   )Lexiconhelpline)merge_dicts	copy_dict)Context)Taskc                   @   s  e Zd ZdZdededdfddZdJded	ee ddfd
dZdefddZ	de
defddZdefddZe				dKded	ee deeeef  dee dee dd fddZ			dLddd	ee deeedf  dee ddf
ddZ		dMd d d	ee dee ddfd!d"Zd	eddfd#d$Zd%edeeef fd&d'Zd%edd fd(d)ZdJd	ee defd*d+Zd ed,ed-eeef deeeeef f fd.d/Zd	ee deeeeef f fd0d1Zd	edefd2d3Z	dJd4ee dee fd5d6Zd7ed8edefd9d:Zd	edefd;d<Z d=e!de!fd>d?Z"e#deeee f fd@dAZ$dJdBee deeef fdCdDZ%dEeeef ddfdFdGZ&deeef fdHdIZ'dS )N
Collectionzg
    A collection of executable tasks. See :doc:`/concepts/namespaces`.

    .. versionadded:: 1.0
    argskwargsreturnNc                 O   s   t  | _t  | _d| _d| _i | _|dd| _|dd| _| jdu r'd| _t	|}|r=t
|d tr=| |d| _|D ]}| | q?| D ]
\}}| || qKdS )a  
        Create a new task collection/namespace.

        `.Collection` offers a set of methods for building a collection of
        tasks from scratch, plus a convenient constructor wrapping said API.

        In either case:

        * The first positional argument may be a string, which (if given) is
          used as the collection's default name when performing namespace
          lookups;
        * A ``loaded_from`` keyword argument may be given, which sets metadata
          indicating the filesystem path the collection was loaded from. This
          is used as a guide when loading per-project :ref:`configuration files
          <config-hierarchy>`.
        * An ``auto_dash_names`` kwarg may be given, controlling whether task
          and collection names have underscores turned to dashes in most cases;
          it defaults to ``True`` but may be set to ``False`` to disable.

          The CLI machinery will pass in the value of the
          ``tasks.auto_dash_names`` config value to this kwarg.

        **The method approach**

        May initialize with no arguments and use methods (e.g.
        `.add_task`/`.add_collection`) to insert objects::

            c = Collection()
            c.add_task(some_task)

        If an initial string argument is given, it is used as the default name
        for this collection, should it be inserted into another collection as a
        sub-namespace::

            docs = Collection('docs')
            docs.add_task(doc_task)
            ns = Collection()
            ns.add_task(top_level_task)
            ns.add_collection(docs)
            # Valid identifiers are now 'top_level_task' and 'docs.doc_task'
            # (assuming the task objects were actually named the same as the
            # variables we're using :))

        For details, see the API docs for the rest of the class.

        **The constructor approach**

        All ``*args`` given to `.Collection` (besides the abovementioned
        optional positional 'name' argument and ``loaded_from`` kwarg) are
        expected to be `.Task` or `.Collection` instances which will be passed
        to `.add_task`/`.add_collection` as appropriate. Module objects are
        also valid (as they are for `.add_collection`). For example, the below
        snippet results in the same two task identifiers as the one above::

            ns = Collection(top_level_task, Collection('docs', doc_task))

        If any ``**kwargs`` are given, the keywords are used as the initial
        name arguments for the respective values::

            ns = Collection(
                top_level_task=some_other_task,
                docs=Collection(doc_task)
            )

        That's exactly equivalent to::

            docs = Collection(doc_task)
            ns = Collection()
            ns.add_task(some_other_task, 'top_level_task')
            ns.add_collection(docs, 'docs')

        See individual methods' API docs for details.
        Nloaded_fromauto_dash_namesTr   )r
   taskscollectionsdefaultname_configurationpopr   r   list
isinstancestr	transform_add_objectitems)selfr   r   _argsargr   obj r&   D/var/www/html/venv/lib/python3.10/site-packages/invoke/collection.py__init__   s"   K
zCollection.__init__r%   r   c                 C   sJ   t |tr	| j}nt |ttfr| j}n	tdt||||d d S )NzNo idea how to insert {!r}!r   )	r   r   add_taskr   r   add_collection	TypeErrorformattype)r"   r%   r   methodr&   r&   r'   r    t   s   
zCollection._add_objectc                 C   sB   t | j }dd | j D }d| jdt|t| S )Nc                 S   s   g | ]}d  |qS )z{}...)r-   .0xr&   r&   r'   
<listcomp>       z'Collection.__repr__.<locals>.<listcomp>z<Collection {!r}: {}>z, )r   r   keysr   r-   r   joinsorted)r"   
task_namesr   r&   r&   r'   __repr__~   s
   zCollection.__repr__otherc                 C   s2   t |tr| j|jko| j|jko| j|jkS dS )NF)r   r   r   r   r   )r"   r:   r&   r&   r'   __eq__   s   


zCollection.__eq__c                 C   s
   t | jS N)boolr8   r"   r&   r&   r'   __bool__   s   
zCollection.__bool__moduleconfigr   r   c                    s  j dd ddtt ddf fdd}d	D ]B}t|d}|r_t|tr_||jd
}	|	|j	|	_	|	|j
|	_
|jrI|	|jnd|	_t|j}
|rXt|
| |
|	_|	  S qtdd t }| }|D ]}|| qp|r|| |S )a#  
        Return a new `.Collection` created from ``module``.

        Inspects ``module`` for any `.Task` instances and adds them to a new
        `.Collection`, returning it. If any explicit namespace collections
        exist (named ``ns`` or ``namespace``) a copy of that collection object
        is preferentially loaded instead.

        When the implicit/default collection is generated, it will be named
        after the module's ``__name__`` attribute, or its last dotted section
        if it's a submodule. (I.e. it should usually map to the actual ``.py``
        filename.)

        Explicitly given collections will only be given that module-derived
        name if they don't already have a valid ``.name`` attribute.

        If the module has a docstring (``__doc__``) it is copied onto the
        resulting `.Collection` (and used for display in help, list etc
        output.)

        :param str name:
            A string, which if given will override any automatically derived
            collection name (or name set on the module's root namespace, if it
            has one.)

        :param dict config:
            Used to set config options on the newly created `.Collection`
            before returning it (saving you a call to `.configure`.)

            If the imported module had a root namespace object, ``config`` is
            merged on top of it (i.e. overriding any conflicts.)

        :param str loaded_from:
            Identical to the same-named kwarg from the regular class
            constructor - should be the path where the module was
            found.

        :param bool auto_dash_names:
            Identical to the same-named kwarg from the regular class
            constructor - determines whether emitted names are auto-dashed.

        .. versionadded:: 1.0
        .Nobj_namer   r   c                    s4   p| pg}t  d}|i |}j|_|S )N)r   r   )dict__doc__)rD   r   r   instancer   clsr   r@   module_namer   r&   r'   instantiate   s   z+Collection.from_module.<locals>.instantiate)ns	namespace)rD   c                 S   s
   t | tS r<   )r   r   r2   r&   r&   r'   <lambda>      
 z(Collection.from_module.<locals>.<lambda>r<   )__name__splitr   r   getattrr   r   r   _transform_lexiconr   r   r   r   r   r   r   filtervarsvaluesr*   	configure)rI   r@   r   rA   r   r   rK   	candidater%   ret
obj_configr   
collectiontaskr&   rH   r'   from_module   s.   4&


zCollection.from_moduler]   r   aliases.r   c                 C   s   |du r$|j r|j }nt|jdr|jj}nt|jdr |j}ntd| |}|| jv r7d}t|||| j	|< t
|jt
|pDg  D ]}| j	j| ||d qG|du s`|du rj|jrl| | || _dS dS dS )a  
        Add `.Task` ``task`` to this collection.

        :param task: The `.Task` object to add to this collection.

        :param name:
            Optional string name to bind to (overrides the task's own
            self-defined ``name`` attribute and/or any Python identifier (i.e.
            ``.func_name``.)

        :param aliases:
            Optional iterable of additional names to bind the task as, on top
            of the primary name. These will be used in addition to any aliases
            the task itself declares internally.

        :param default: Whether this task should be the collection default.

        .. versionadded:: 1.0
        N	func_namerQ   z&Could not obtain a name for this task!zFName conflict: this collection has a sub-collection named {!r} already)toT)r   hasattrbodyr`   rQ   
ValueErrorr   r   r-   r   r   r_   alias
is_default_check_default_collisionr   )r"   r]   r   r_   r   errre   r&   r&   r'   r*      s&   





zCollection.add_taskcollc                 C   sv   t |tr
t|}|p|j}|std| |}|| jv r(d}t|||| j	|< |r9| 
| || _dS dS )a  
        Add `.Collection` ``coll`` as a sub-collection of this one.

        :param coll: The `.Collection` to add.

        :param str name:
            The name to attach the collection as. Defaults to the collection's
            own internal name.

        :param default:
            Whether this sub-collection('s default task-or-collection) should
            be the default invocation of the parent collection.

        .. versionadded:: 1.0
        .. versionchanged:: 1.5
            Added the ``default`` parameter.
        z&Non-root collections must have a name!z<Name conflict: this collection has a task named {!r} alreadyN)r   r   r   r^   r   rd   r   r   r-   r   rg   r   )r"   ri   r   r   rh   r&   r&   r'   r+     s   







zCollection.add_collectionc                 C   s    | j rd}t||| j d S )Nz3'{}' cannot be the default because '{}' already is!)r   rd   r-   )r"   r   msgr&   r&   r'   rg   F  s   z#Collection._check_default_collisionpathc                 C   s&   | d}|d}d|}||fS )aB  
        Obtain first collection + remainder, of a task path.

        E.g. for ``"subcollection.taskname"``, return ``("subcollection",
        "taskname")``; for ``"subcollection.nested.taskname"`` return
        ``("subcollection", "nested.taskname")``, etc.

        An empty path becomes simply ``('', '')``.
        rB   r   )rR   r   r6   )r"   rk   partsri   restr&   r&   r'   _split_pathK  s   



zCollection._split_pathc                 C   s*   | d}| }|r|j|d }|s	|S )zp
        Given a ``path`` to a subcollection, return that subcollection.

        .. versionadded:: 1.0
        rB   r   )rR   r   r   )r"   rk   rl   r\   r&   r&   r'   subcollection_from_pathZ  s   
z"Collection.subcollection_from_pathc                 C   s   |  |d S )a  
        Returns task named ``name``. Honors aliases and subcollections.

        If this collection has a default task, it is returned when ``name`` is
        empty or ``None``. If empty input is given and no task has been
        selected as the default, ValueError will be raised.

        Tasks within subcollections should be given in dotted form, e.g.
        'foo.bar'. Subcollection default tasks will be returned on the
        subcollection's name.

        .. versionadded:: 1.0
        r   )task_with_configr"   r   r&   r&   r'   __getitem__f  s   zCollection.__getitem__rm   oursc                 C   s(   | j | |\}}|t|fi |fS r<   )r   rp   rE   )r"   ri   rm   rs   r]   rA   r&   r&   r'   _task_with_merged_configv  s   z#Collection._task_with_merged_configc                 C   s|   |   }|s| jstd| | j |fS | |}d|v r+| |\}}| |||S || jv r7| |d|S | j| |fS )a  
        Return task named ``name`` plus its configuration dict.

        E.g. in a deeply nested tree, this method returns the `.Task`, and a
        configuration dict created by merging that of this `.Collection` and
        any nested `Collections <.Collection>`, up through the one actually
        holding the `.Task`.

        See `~.Collection.__getitem__` for semantics of the ``name`` argument.

        :returns: Two-tuple of (`.Task`, `dict`).

        .. versionadded:: 1.0
        z$This collection has no default task.rB    )configurationr   rd   r   rn   rt   r   r   )r"   r   rs   ri   rm   r&   r&   r'   rp   |  s   

zCollection.task_with_configc                 C   s$   z| |  W dS  t y   Y dS w )NTF)KeyErrorrq   r&   r&   r'   __contains__  s   zCollection.__contains__ignore_unknown_helpc              	   C   s@   g }| j  D ]\}}| | }|t|||j|dd q|S )aw  
        Returns all contained tasks and subtasks as a list of parser contexts.

        :param bool ignore_unknown_help:
            Passed on to each task's ``get_arguments()`` method. See the config
            option by the same name for details.

        .. versionadded:: 1.0
        .. versionchanged:: 1.7
            Added the ``ignore_unknown_help`` kwarg.
        )ry   )r   r_   r   )r8   r!   appendParserContextget_arguments)r"   ry   resultprimaryr_   r]   r&   r&   r'   to_contexts  s   	zCollection.to_contextscollection_name	task_namec                 C   s   d | || |gS )NrB   )r6   r   )r"   r   r   r&   r&   r'   subtask_name  s   zCollection.subtask_namec                 C   s   |s|S d\}}| j sd\}}g }t|d }t|D ]%\}}|d|fvr;||kr;||d  dkr;||d  dkr;|}|| qd|S )a  
        Transform ``name`` with the configured auto-dashes behavior.

        If the collection's ``auto_dash_names`` attribute is ``True``
        (default), all non leading/trailing underscores are turned into dashes.
        (Leading/trailing underscores tend to get stripped elsewhere in the
        stack.)

        If it is ``False``, the inverse is applied - all dashes are turned into
        underscores.

        .. versionadded:: 1.0
        )_-)r   r   r	   r   rB   ru   )r   len	enumeraterz   r6   )r"   r   from_ra   replacedendicharr&   r&   r'   r     s   
zCollection.transformoldc                 C   s^   t  }| D ]\}}t||| |< q|j D ]\}}|j| || |d q|S )zr
        Take a Lexicon and apply `.transform` to its keys and aliases.

        :returns: A new Lexicon.
        )r   ra   )r
   r!   copydeepcopyr   r_   re   )r"   r   newkeyvaluer&   r&   r'   rT     s   zCollection._transform_lexiconc                    s   i }j  D ]\}}ttj|j||< qj D ],\ }|j D ]"\}}tt fdd|}|j|kr?| f7 }||	 |< q%q|S )a  
        Return all task identifiers for this collection as a one-level dict.

        Specifically, a dict with the primary/"real" task names as the key, and
        any aliases as a list value.

        It basically collapses the namespace tree into a single
        easily-scannable collection of invocation strings, and is thus suitable
        for things like flat-style task listings or transformation into parser
        contexts.

        .. versionadded:: 1.0
        c                    s     | S r<   )r   rN   	coll_namer"   r&   r'   rO     s    z'Collection.task_names.<locals>.<lambda>)
r   r!   r   mapr   r_   r   r8   r   r   )r"   rZ   r   r]   ri   r   r_   r&   r   r'   r8      s   

	zCollection.task_namestaskpathc                 C   s    |du r	t | jS | |d S )a  
        Obtain merged configuration values from collection & children.

        :param taskpath:
            (Optional) Task name/path, identical to that used for
            `~.Collection.__getitem__` (e.g. may be dotted for nested tasks,
            etc.) Used to decide which path to follow in the collection tree
            when merging config values.

        :returns: A `dict` containing configuration values.

        .. versionadded:: 1.0
        Nr	   )r   r   rp   )r"   r   r&   r&   r'   rv      s   
zCollection.configurationoptionsc                 C   s   t | j| dS )a7  
        (Recursively) merge ``options`` into the current `.configuration`.

        Options configured this way will be available to all tasks. It is
        recommended to use unique keys to avoid potential clashes with other
        config options

        For example, if you were configuring a Sphinx docs build target
        directory, it's better to use a key like ``'sphinx.target'`` than
        simply ``'target'``.

        :param options: An object implementing the dictionary protocol.
        :returns: ``None``.

        .. versionadded:: 1.0
        N)r   r   )r"   r   r&   r&   r'   rX   2  s   zCollection.configurec              	      sT    j t  j fddt j dd dD dd t j dd dD dS )	z
        Return an appropriate-for-serialization version of this object.

        See the documentation for `.Program` and its ``json`` task listing
        format; this method is the driver for that functionality.

        .. versionadded:: 1.0
        c                    s4   g | ]}  |jt| fd d|jD dqS )c                    s   g | ]}  |qS r&   )r   )r1   yr>   r&   r'   r3   V  r4   z4Collection.serialized.<locals>.<listcomp>.<listcomp>)r   helpr_   )r   r   r   r_   r0   r>   r&   r'   r3   R  s    
z)Collection.serialized.<locals>.<listcomp>c                 S   s   | j S r<   r)   rN   r&   r&   r'   rO   X  s    z'Collection.serialized.<locals>.<lambda>)r   c                 S   s   g | ]}|  qS r&   )
serializedr0   r&   r&   r'   r3   Z  s    c                 S   s
   | j pdS )Nru   r)   rN   r&   r&   r'   rO   ]  rP   )r   r   r   r   r   )r   r   r   r7   r   rW   r   r>   r&   r>   r'   r   E  s   

zCollection.serializedr<   )NNNN)NNN)NN)(rQ   
__module____qualname__rF   r   r(   r   r   r    r9   objectr=   r;   r?   classmethodr   r   r^   r   r*   r+   rg   rn   ro   rr   rt   rp   rx   r   r{   r   r   r   r
   rT   propertyr8   rv   rX   r   r&   r&   r&   r'   r      s    a
	_
2
)


$
' r   )r   typesr   typingr   r   r   r   r   r   utilr
   r   rA   r   r   parserr   r{   r   r   r   r&   r&   r&   r'   <module>   s     