o
    Th!                     @   s  d dl Z d dlZd dl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
mZmZmZmZmZmZ ddlmZmZmZmZ ddlmZmZ ddlmZmZmZ ddlmZmZm Z m!Z! dd	l"m#Z# dd
l$m%Z%m&Z&m'Z' e	rddl(m)Z) ddlm*Z* ddl$m+Z+ G dd dZ,dS )    N)import_module)TYPE_CHECKINGAnyDictListOptionalSequenceTupleType   )
CollectionConfigExecutorFilesystemLoader)completeprint_completion_script)ParserParserContextArgument)UnexpectedExitCollectionNotFound
ParseErrorExit)pty_size)debugenable_logginghelpline)Loader)ParseResult)Lexiconc                   @   s  e Zd ZU dZded< ded fddZded fdd	Zee ed
< dZ	de	 Z
dZde ZdZ								dhdee ded dee dee deed  deed  deed  deee  ddfddZdiddZdjd!eddfd"d#Zdkd
eee  d$eddfd%d&Zd
eee  ddfd'd(Zdid)d*Zdid+d,Zdid-d.Zdid/d0Zd
eee  ddfd1d2Zedefd3d4Zedefd5d6Zedefd7d8Zedee fd9d:Zedld<d=Z ede!fd>d?Z"did@dAZ#didBdCZ$didDdEZ%didFdGZ&dHe!dIe'ee(f ddfdJdKZ)de*fdLdMZ+didNdOZ,deddfdPdQZ-didRdSZ.didTdUZ/didVdWZ0	dmdXddYeee  dee1eee f  fdZd[Z2did\d]Z3dnd_edefd`daZ4	^dndbe5e1eee f  d_eddfdcddZ6dee5e1eee f  ddfdfdgZ7dS )oProgramau  
    Manages top-level CLI invocation, typically via ``setup.py`` entrypoints.

    Designed for distributing Invoke task collections as standalone programs,
    but also used internally to implement the ``invoke`` program itself.

    .. seealso::
        :ref:`reusing-as-a-binary` for a tutorial/walkthrough of this
        functionality.

    .. versionadded:: 1.0
    r   corereturnr   c                 C   s   t dtddt dtdddt dd	d
t dtdddt dtdddt dtdddt ddddt ddd
t ddddt dtdddt ddddt d td!d"dt d#tdd$dt d%tdd&dt d'tdd(dt d)tdd*dt d+tdd,dgS )-zd
        Return default core `.Argument` objects, as a list.

        .. versionadded:: 1.0
        )command-timeoutTz7Specify a global command execution timeout, in seconds.)nameskindhelp)r   Fz:Print tab-completion candidates for given parse remainder.r%   r&   defaultr'   )configfz"Runtime configuration file to use.r%   r'   )r   dzEnable debug output.)dryRz!Echo commands instead of running.)echoez&Echo executed commands before running.)r'   hTz$Show core or per-task help and exit.)r%   optionalr'   )hidez*Set default value of run()'s 'hide' kwarg.)listlz8List available tasks, optionally limited to a namespace.)
list-depthDr   z3When listing tasks, only show the first INT levels.)list-formatFzbChange the display format used when listing tasks. Should be one of: flat (default), nested, json.flat)r%   r'   r)   )print-completion-script zIPrint the tab-completion script for your preferred shell (bash|zsh|fish).)prompt-for-sudo-passwordzCPrompt user at start of session for the sudo.password config value.)ptypz(Use a pty when executing shell commands.)versionVzShow version and exit.)	warn-onlywz3Warn, instead of failing, when shell commands fail.)	write-pyczEnable creation of .pyc files.)r   intboolstrself rK   A/var/www/html/venv/lib/python3.10/site-packages/invoke/program.py	core_args0   s   zProgram.core_argsc                 C   s&   t dddt dtdddt dd	dgS )
aU  
        Return default task-related `.Argument` objects, as a list.

        These are only added to the core args in "task runner" mode (the
        default for ``invoke`` itself) - they are omitted when the constructor
        is given a non-empty ``namespace`` argument ("bundled namespace" mode).

        .. versionadded:: 1.0
        )
collectioncz Specify collection name to load.r,   )	no-dedupeFzDisable task deduplication.r(   )search-rootrz4Change root directory used for finding task modules.)r   rG   rI   rK   rK   rL   	task_args   s   zProgram.task_argsargv          NrA   	namespacer   namebinaryloader_classr   executor_classr   config_classr   binary_namesc	           	      C   sR   |du rdn|| _ || _|| _|| _|| _g | _|pt| _|p t| _	|p%t
| _dS )a^  
        Create a new, parameterized `.Program` instance.

        :param str version:
            The program's version, e.g. ``"0.1.0"``. Defaults to ``"unknown"``.

        :param namespace:
            A `.Collection` to use as this program's subcommands.

            If ``None`` (the default), the program will behave like ``invoke``,
            seeking a nearby task namespace with a `.Loader` and exposing
            arguments such as :option:`--list` and :option:`--collection` for
            inspecting or selecting specific namespaces.

            If given a `.Collection` object, will use it as if it had been
            handed to :option:`--collection`. Will also update the parser to
            remove references to tasks and task-related options, and display
            the subcommands in ``--help`` output. The result will be a program
            that has a static set of subcommands.

        :param str name:
            The program's name, as displayed in ``--version`` output.

            If ``None`` (default), is a capitalized version of the first word
            in the ``argv`` handed to `.run`. For example, when invoked from a
            binstub installed as ``foobar``, it will default to ``Foobar``.

        :param str binary:
            Descriptive lowercase binary name string used in help text.

            For example, Invoke's own internal value for this is ``inv[oke]``,
            denoting that it is installed as both ``inv`` and ``invoke``. As
            this is purely text intended for help display, it may be in any
            format you wish, though it should match whatever you've put into
            your ``setup.py``'s ``console_scripts`` entry.

            If ``None`` (default), uses the first word in ``argv`` verbatim (as
            with ``name`` above, except not capitalized).

        :param binary_names:
            List of binary name strings, for use in completion scripts.

            This list ensures that the shell completion scripts generated by
            :option:`--print-completion-script` instruct the shell to use
            that completion for all of this program's installed names.

            For example, Invoke's internal default for this is ``["inv",
            "invoke"]``.

            If ``None`` (the default), the first word in ``argv`` (in the
            invocation of :option:`--print-completion-script`) is used in a
            single-item list.

        :param loader_class:
            The `.Loader` subclass to use when loading task collections.

            Defaults to `.FilesystemLoader`.

        :param executor_class:
            The `.Executor` subclass to use when executing tasks.

            Defaults to `.Executor`; may also be overridden at runtime by the
            :ref:`configuration system <default-values>` and its
            ``tasks.executor_class`` setting (anytime that setting is not
            ``None``).

        :param config_class:
            The `.Config` subclass to use for the base config object.

            Defaults to `.Config`.

        .. versionchanged:: 1.2
            Added the ``binary_names`` argument.
        Nunknown)rA   rY   _name_binary_binary_namesrT   r   r\   r   r]   r   r^   )	rJ   rA   rY   rZ   r[   r\   r]   r^   r_   rK   rK   rL   __init__   s   U

zProgram.__init__c                 C   s   |   | _dS )a  
        Instantiate a `.Config` (or subclass, depending) for use in task exec.

        This Config is fully usable but will lack runtime-derived data like
        project & runtime config files, CLI arg overrides, etc. That data is
        added later in `update_config`. See `.Config` docstring for lifecycle
        details.

        :returns: ``None``; sets ``self.config`` instead.

        .. versionadded:: 1.0
        N)r^   r*   rI   rK   rK   rL   create_config  s   zProgram.create_configTmergec           
      C   s6  i }| j d jrd|d< | j jjrd|d< | j jjr!| j jj|d< | j jjr*d|d< | j jjr3d|d< i }d| j v rD| j d jrDd	|d
< i }| j d j}|rR||d< i }| j d jrcd}t||d< t||||d}| jj	|d	d | j jj}	|	du rt
jdd}	| j|	 | jjd	d |r| j  dS dS )as  
        Update the previously instantiated `.Config` with parsed data.

        For example, this is how ``--echo`` is able to override the default
        config value for ``run.echo``.

        :param bool merge:
            Whether to merge at the end, or defer. Primarily useful for
            subclassers. Default: ``True``.

        .. versionadded:: 1.0
        rC   Twarnr?   r4   r0   r.   rP   Fdeduper#   commandr>   z&Desired 'sudo.password' config value: password)runtaskssudotimeouts)rf   NINVOKE_RUNTIME_CONFIG)argsvaluer?   r4   r0   r.   getpassdictr*   load_overridesosenvirongetset_runtime_pathload_runtimerf   )
rJ   rf   rk   rl   rn   ri   rm   prompt	overridesruntime_pathrK   rK   rL   update_config.  s@   




zProgram.update_configexitc              
   C   sL  z |    | | |   |   |   |   |   W dS  ttt	fy } zht
d| t|t	r>t|tjd t|trN|jrNt|jtjd t|tr_|jjr_t|tjdd |rt|trk|jj}nt|trt|j}nt|t	r{d}t| nt
d W Y d}~dS W Y d}~dS d}~w ty   td Y dS w )a  
        Execute main CLI logic, based on ``argv``.

        :param argv:
            The arguments to execute against. May be ``None``, a list of
            strings, or a string. See `.normalize_argv` for details.

        :param bool exit:
            When ``False`` (default: ``True``), will ignore `.ParseError`,
            `.Exit` and `.Failure` exceptions, which otherwise trigger calls to
            `sys.exit`.

            .. note::
                This is mostly a concession to testing. If you're setting this
                to ``False`` in a production setting, you should probably be
                using `.Executor` and friends directly instead!

        .. versionadded:: 1.0
        z-Received a possibly-skippable exception: {!r})filer=   )r   endr   z3Invoked as run(..., exit=False), ignoring exceptionN)re   
parse_coreparse_collectionparse_tasksparse_cleanupr}   executer   r   r   r   format
isinstanceprintsysstderrmessageresultr4   exitedcoder~   KeyboardInterrupt)rJ   rT   r~   r1   r   rK   rK   rL   rk   c  s<   





zProgram.runc                 C   s   t d| | | |   t d | jd j t_| jj jr$t  | jj	jr3t d | 
  t| jd jrFt| jd j| jd td S )Nzargv given to Program.run: {!r}zFinished parsing core argsrE   z)Saw --version, printing version & exitingr<   )shellr%   )r   r   normalize_argvparse_core_argsrp   rq   r   dont_write_bytecoder   rA   print_versionr   r   r_   rJ   rT   rK   rK   rL   r     s$   



zProgram.parse_corec                 C   sl   | j durtd | j | _ntd | jjjdu r#td |   t|   d| _	d| _
d| _| j| _dS )z`
        Load a tasks collection & project-level config.

        .. versionadded:: 1.0
        Nz;Program was given default namespace, not loading collectionz;No default namespace provided, trying to load one from diskTz8No bundled namespace & bare --help given; printing help.r;   )rY   r   rN   rp   r'   rq   
print_helpr   load_collection	list_root
list_depthlist_formatscoped_collectionrI   rK   rK   rL   r     s&   

zProgram.parse_collectionc                 C   s&  | j jj}|du rtd |   t|r/|| jjv r(d}t| | | tt	d
|| j jj}| j d j| _| j d j| _|rnt|trh|| _z| j|}|| _W n tyg   d}t|
|w |   t| j jjrt| j| j| j| j|  d | js| jjs|   d	S d	S d	S )
zo
        Post-parsing, pre-execution steps such as --help, --list, etc.

        .. versionadded:: 1.0
        Tz(Saw bare --help, printing help & exitingz7Saw --help <taskname>, printing per-task help & exitingzNo idea what '{}' is!r9   r7   zSub-collection '{}' not found!)r%   r!   initial_contextrN   parserN)rp   r'   rq   r   r   r   r   contextsprint_task_helpr   r   r5   r   r   r   rH   r   rN   subcollection_from_pathr   KeyError
list_tasksr   r_   r!   r   _make_parserrl   r)   no_tasks_given)rJ   halpmsgr   subrK   rK   rL   r     sL   





zProgram.parse_cleanupc                 C   s   t d |   t)NzVNo tasks specified for execution and no default task; printing global help as fallback)r   r   r   rI   rK   rK   rL   r   (  s
   zProgram.no_tasks_givenc                 C   s\   | j }| jjj }|dur|d\}}}t|}t||}|| j| j| j}|j| j  dS )a  
        Hand off data & tasks-to-execute specification to an `.Executor`.

        .. note::
            Client code just wanting a different `.Executor` subclass can just
            set ``executor_class`` in `.__init__`, or override
            ``tasks.executor_class`` anywhere in the :ref:`config system
            <default-values>` (which may allow you to avoid using a custom
            Program entirely).

        .. versionadded:: 1.0
        N.)	r]   r*   rl   
rpartitionr   getattrrN   r!   r   )rJ   klassconfig_pathmodule_path_
class_namemoduleexecutorrK   rK   rL   r   /  s   

zProgram.executec                 C   sH   |du rt j}td| nt|tr| }td| || _dS )a  
        Massages ``argv`` into a useful list of strings.

        **If None** (the default), uses `sys.argv`.

        **If a non-string iterable**, uses that in place of `sys.argv`.

        **If a string**, performs a `str.split` and then executes with the
        result. (This is mostly a convenience; when in doubt, use a list.)

        Sets ``self.argv`` to the result.

        .. versionadded:: 1.0
        Nz#argv was None; using sys.argv: {!r}z%argv was string-like; splitting: {!r})r   rT   r   r   r   rH   splitr   rK   rK   rL   r   I  s   

zProgram.normalize_argvc                 C   s   | j p| j S )zi
        Derive program's human-readable name based on `.binary`.

        .. versionadded:: 1.0
        )ra   r[   
capitalizerI   rK   rK   rL   rZ   `  s   zProgram.namec                 C   s   | j rtj| j d S dS )z
        Returns the program name we were actually called as.

        Specifically, this is the (Python's os module's concept of a) basename
        of the first argument in the parsed argument vector.

        .. versionadded:: 1.2
        r   r=   )rT   ru   pathbasenamerI   rK   rK   rL   	called_asi  s   zProgram.called_asc                 C   s   | j p| jS )zu
        Derive program's help-oriented binary name(s) from init args & argv.

        .. versionadded:: 1.0
        )rb   r   rI   rK   rK   rL   r[   v     zProgram.binaryc                 C   s   | j p| jgS )zv
        Derive program's completion-oriented binary name(s) from args & argv.

        .. versionadded:: 1.2
        )rc   r   rI   rK   rK   rL   r_     s   zProgram.binary_namesr   c                 C   s   | j d jS )zj
        Obtain core program args from ``self.core`` parse result.

        .. versionadded:: 1.0
        r   )r!   rp   rI   rK   rK   rL   rp     r   zProgram.argsc                 C   s(   |   }| jdu r||  7 }t|dS )z
        The initial parser context, aka core program flags.

        The specific arguments contained therein will differ depending on
        whether a bundled namespace was specified in `.__init__`.

        .. versionadded:: 1.0
        N)rp   )rM   rY   rS   r   )rJ   rp   rK   rK   rL   r     s   


zProgram.initial_contextc                 C   s   t d| j| jp	d d S )N{} {}r`   )r   r   rZ   rA   rI   rK   rK   rL   r     s   zProgram.print_versionc                 C   sf   d}| j d ur	d}td| j| td td td | | j  | j d ur1|   d S d S )Nz-task1 [--task1-opts] ... taskN [--taskN-opts]z$<subcommand> [--subcommand-opts] ...zUsage: {} [--core-opts] {}r=   zCore options:)rY   r   r   r[   print_columnsr   help_tuplesr   )rJ   usage_suffixrK   rK   rL   r     s   

zProgram.print_helpc                 C   sJ   t d t| jdd}|| jdd | _d}t || j| jj dS )z
        Filter out core args, leaving any tasks or their args for later.

        Sets ``self.core`` to the `.ParseResult` from this step.

        .. versionadded:: 1.0
        z#Parsing initial context (core args)T)initialignore_unknownr   Nz-Core-args parse result: {!r} & unparsed: {!r})r   r   r   
parse_argvrT   r!   r   unparsed)rJ   r   r   rK   rK   rL   r     s
   zProgram.parse_core_argsc              
   C   s   | j d j}| j| j|d}| j jj}z!||\}}| j| | j  tj	||| jj
jd| _W dS  tyH } ztd|jd}~ww )zq
        Load a task collection based on parsed core args, or die trying.

        .. versionadded:: 1.0
        rQ   )r*   start)loaded_fromauto_dash_namesz%Can't find any collection named {!r}!N)rp   rq   r\   r*   rN   loadset_project_locationload_projectr   from_modulerl   r   r   r   r   rZ   )rJ   r   loader	coll_namer   parentr1   rK   rK   rL   r     s$   

zProgram.load_collectioncontextnew_argsc                 C   s*   |  D ]\}}|jr|j|j| _qd S N)items	got_value_valuerp   )rJ   r   r   keyargrK   rK   rL   _update_core_context  s
   zProgram._update_core_contextc                 C   s   t | j| jj| jjjddS )N)ignore_unknown_help)r   r   )r   r   rN   to_contextsr*   rl   r   rI   rK   rK   rL   r     s   zProgram._make_parserc                 C   sh   |   | _td| j | j| jj}|d| _	| j
| jd | j	jd || _td| j dS )a  
        Parse leftover args, which are typically tasks & per-task args.

        Sets ``self.parser`` to the parser used, ``self.tasks`` to the
        parsed per-task contexts, and ``self.core_via_tasks`` to a context
        holding any core flags seen within the task contexts.

        Also modifies ``self.core`` to include the data from ``core_via_tasks``
        (so that it correctly reflects any supplied core flags regardless of
        where they appeared).

        .. versionadded:: 1.0
        zParsing tasks against {!r}r   )r   r   zResulting task contexts: {!r}N)r   r   r   r   rN   r   r!   r   popcore_via_tasksr   rp   rl   )rJ   r   rK   rK   rL   r     s   
zProgram.parse_tasksc                 C   s   | j j| }| }t| j| }d}|rdnd}t|| j|| td td |rJ|	 D ]}|
 r@t| j|  q2td q2td nt| jd  td td |rb| | dS t| jd  td dS )zp
        Print help for a specific task, e.g. ``inv --help <taskname>``.

        .. versionadded:: 1.0
        z3Usage: {} [--core-opts] {} {}[other tasks here ...]z[--options] r=   z
Docstring:nonezOptions:N)r   r   r   inspectgetdocrN   r   r   r[   
splitlinesstripleading_indentr   )rJ   rZ   ctxtuples	docstringheaderoptslinerK   rK   rL   r     s*   

zProgram.print_task_helpc                 C   s6   | j }|sd}t||jt| d| j  d S )Nz"No tasks found in collection '{}'!zlist_{})r   r   r   rZ   r   r   )rJ   focusr   rK   rK   rL   r   '  s
   zProgram.list_tasksc                 C   s   |  | j}| j|d d S )N)pairs_make_pairsr   display_with_columns)rJ   r   rK   rK   rL   	list_flat1  s   zProgram.list_flatc                 C   s"   |  | j}d}| j||d d S )Nz'*' denotes collection defaults)r   extrar   )rJ   r   r   rK   rK   rL   list_nested5  s   zProgram.list_nestedcoll	ancestorsc                    s  |d u rg }g }t || j }ddd |D }t|j D ]r\}}||jk}|}	tt|j	t|j
}
|s;| jrGd|	}	dd |
D }
| jdkrT| |rT|	d7 }	| jd	krw|  rd| jrdd    fd
d|
D }
|rw|rw|
d  |
rdd|
nd} |	 | }||t|f q | jot |d | jk}t|j D ]Y\}|}	|s| jrd|	}	|rˇfdddD }|	dd|7 }	| jdkr|||	 tf n| jd	kr|r|||	 tf |s| j||g d}|| q|S )Nr   c                 s   s    | ]}|V  qd S r   rK   .0xrK   rK   rL   	<genexpr>C  s    z&Program._make_pairs.<locals>.<genexpr>.{}c                 S   s   g | ]}d  |qS )r   )r   r   rK   rK   rL   
<listcomp>O  s    z'Program._make_pairs.<locals>.<listcomp>nested*r;   c                    s   g | ]} | qS rK   rK   )r   alias)prefixrK   rL   r   ^  s    r   z ({})z, r=   r   c                    s,   g | ]}t  |rd tt  ||qS )r   )r   r   len)r   attr)subcollrK   rL   r   l  s    )rl   collectionsz [{}])r   r   )r   indentjoinsortedrl   r   r)   r5   map	transformaliasesr   r   r   insertappendr   r   r   r   extend)rJ   r   r   r   r   ancestor_pathrZ   task
is_defaultdisplaynamer   	alias_strfulltruncatetalliesrecursed_pairsrK   )r   r   rL   r   :  s^   











zProgram._make_pairsc                 C   s.   | j rtd| j}| }tt| d S )Nz:The --list-depth option is not supported with JSON format!)r   r   r   
serializedr   jsondumps)rJ   r   datarK   rK   rL   	list_json  s   zProgram.list_jsonr=   r   c           	      C   sx   | j }| j}|rd|nd}d}|s|r-|rd|nd}|r$|r$dnd}d|||}d||}| jd ur:d}|S )N '{}'r=   zdepth={}z; z	 ({}{}{})zAvailable{} tasks{}Subcommands)r   r   r   rY   )	rJ   r   rootdepth	specifiertaildepthstrjoinertextrK   rK   rL   task_list_opener  s   
zProgram.task_list_openerr   c                 C   sf   | j }td| j|d | | | jj}|r1d}|r'd|}d|}td|| d S d S )Nz{}:
)r   r=   r  r   zDefault{} task: {}
)r   r   r   r  r   r   r)   )rJ   r   r   r  r)   specificrK   rK   rL   r     s   


zProgram.display_with_columnsr   c                 C   s   t dd |D }t d | | j | j d }tj|d}|D ]H\}}|du r*d}||}|t| }d| j	||d | jd f}	|rbt
|	|d   |dd D ]}
t
dt|	 |
  qTq t
|	  q t
d dS )	z
        Print tabbed columns from (name, help) ``tuples``.

        Useful for listing tasks + docstrings, flags + help strings, etc.

        .. versionadded:: 1.0
        c                 s   s    | ]	}t |d  V  qdS )r   N)r   r   rK   rK   rL   r     s    z(Program.print_columns.<locals>.<genexpr>r   r   )widthNr=   rV   )maxr   leading_indent_widthcol_paddingtextwrapTextWrapperwrapr   r   r   r   rstrip)rJ   r   
name_width
desc_widthwrapperrZ   help_strhelp_chunksname_paddingspecchunkrK   rK   rL   r     s>   
	zProgram.print_columns)NNNNNNNN)r"   N)T)NT)r"   r   r   )r=   )8__name__
__module____qualname____doc____annotations__r   rM   rS   rH   r  r   indent_widthr   r   r   r
   rd   re   rG   r}   rk   r   r   r   r   r   r   propertyrZ   r   r[   r_   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	   r   r  r  r   r   r   rK   rK   rK   rL   r        s   
 h



	


a 5E

$
>
	







!





E
r    )-rr   r   r  ru   r   r!  	importlibr   typingr   r   r   r   r   r   r	   r
   r=   r   r   r   r   completion.completer   r   r   r   r   r   
exceptionsr   r   r   r   	terminalsr   utilr   r   r   r   r   r   r   r    rK   rK   rK   rL   <module>   s&    (