B
    MhhH                 @   s  U d dl Z d dlZd dlZd dlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ eejeejf eeeedddZG dd dZdZdZd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jdej e dZ!eeedZ"ej#eej e f e$d < d6e!ej%e e!d!d"d#Z&eej%ej e  d$d%d&Z'e	ee(d'd(d)Z)e	ee(d*d+d,Z*e	ej+e ee(d-d.d/Z,eejeejf eej+e e	d0d1d2Z-e	ej+e eej.ej/eef ef d3d4d5Z0dS )7    N)gettext   )Argument)BaseCommand)Context)MultiCommand)Option)	Parameter)ParameterSource)split_arg_string)echo)clictx_args	prog_namecomplete_varinstructionreturnc       	      C   sf   | d\}}}t|}|dkr$dS || |||}|dkrJt|  dS |dkrbt|  dS dS )a   Perform shell completion for the given CLI program.

    :param cli: Command being called.
    :param ctx_args: Extra arguments to pass to
        ``cli.make_context``.
    :param prog_name: Name of the executable in the shell.
    :param complete_var: Name of the environment variable that holds
        the completion instruction.
    :param instruction: Value of ``complete_var`` with the completion
        instruction and shell, in the form ``instruction_shell``.
    :return: Status code to exit with.
    _Nr   sourcer   complete)	partitionget_completion_classr   r   r   )	r   r   r   r   r   shellr   Zcomp_clscomp r   9/tmp/pip-install-vv81h98y/click/click/shell_completion.pyshell_complete   s    r   c               @   sH   e Zd ZdZdZdejeeje ejddddZ	eejdd	d
Z
dS )CompletionItema)  Represents a completion value and metadata about the value. The
    default metadata is ``type`` to indicate special shell handling,
    and ``help`` if a shell supports showing a help string next to the
    value.

    Arbitrary parameters can be passed when creating the object, and
    accessed using ``item.attr``. If an attribute wasn't passed,
    accessing it returns ``None``.

    :param value: The completion suggestion.
    :param type: Tells the shell script to provide special completion
        support for the type. Click uses ``"dir"`` and ``"file"``.
    :param help: String shown next to the value if supported.
    :param kwargs: Arbitrary metadata. The built-in implementations
        don't use this, but custom type completions paired with custom
        shell support could use it.
    )valuetypehelp_infoplainN)r   r   r    kwargsr   c             K   s   || _ || _|| _|| _d S )N)r   r   r    r!   )selfr   r   r    r#   r   r   r   __init__L   s    zCompletionItem.__init__)namer   c             C   s   | j |S )N)r!   get)r$   r&   r   r   r   __getattr__X   s    zCompletionItem.__getattr__)r"   N)__name__
__module____qualname____doc__	__slots__tAnystrOptionalr%   r(   r   r   r   r   r   7   s    r   a  %(complete_func)s() {
    local IFS=$'\n'
    local response

    response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD %(complete_var)s=bash_complete $1)

    for completion in $response; do
        IFS=',' read type value <<< "$completion"

        if [[ $type == 'dir' ]]; then
            COMPREPLY=()
            compopt -o dirnames
        elif [[ $type == 'file' ]]; then
            COMPREPLY=()
            compopt -o default
        elif [[ $type == 'plain' ]]; then
            COMPREPLY+=($value)
        fi
    done

    return 0
}

%(complete_func)s_setup() {
    complete -o nosort -F %(complete_func)s %(prog_name)s
}

%(complete_func)s_setup;
a  #compdef %(prog_name)s

%(complete_func)s() {
    local -a completions
    local -a completions_with_descriptions
    local -a response
    (( ! $+commands[%(prog_name)s] )) && return 1

    response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) %(complete_var)s=zsh_complete %(prog_name)s)}")

    for type key descr in ${response}; do
        if [[ "$type" == "plain" ]]; then
            if [[ "$descr" == "_" ]]; then
                completions+=("$key")
            else
                completions_with_descriptions+=("$key":"$descr")
            fi
        elif [[ "$type" == "dir" ]]; then
            _path_files -/
        elif [[ "$type" == "file" ]]; then
            _path_files -f
        fi
    done

    if [ -n "$completions_with_descriptions" ]; then
        _describe -V unsorted completions_with_descriptions -U
    fi

    if [ -n "$completions" ]; then
        compadd -U -V unsorted -a completions
    fi
}

if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
    # autoload from fpath, call function directly
    %(complete_func)s "$@"
else
    # eval/source/. command, register function for later
    compdef %(complete_func)s %(prog_name)s
fi
af  function %(complete_func)s;
    set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(prog_name)s);

    for completion in $response;
        set -l metadata (string split "," $completion);

        if test $metadata[1] = "dir";
            __fish_complete_directories $metadata[2];
        else if test $metadata[1] = "file";
            __fish_complete_path $metadata[2];
        else if test $metadata[1] = "plain";
            echo $metadata[2];
        end;
    end;
end;

complete --no-files --command %(prog_name)s --arguments "(%(complete_func)s)";
c               @   s   e Zd ZU dZeje ed< eje ed< eej	eej
f eeddddZeedd	d
Zejeej
f dddZedddZejeje ef dddZeje eeje dddZeedddZedddZdS )ShellCompletea  Base class for providing shell completion support. A subclass for
    a given shell will override attributes and methods to implement the
    completion instructions (``source`` and ``complete``).

    :param cli: Command being called.
    :param prog_name: Name of the executable in the shell.
    :param complete_var: Name of the environment variable that holds
        the completion instruction.

    .. versionadded:: 8.0
    r&   source_templateN)r   r   r   r   r   c             C   s   || _ || _|| _|| _d S )N)r   r   r   r   )r$   r   r   r   r   r   r   r   r%      s    zShellComplete.__init__)r   c             C   s*   t jdd| jddt jd}d| dS )zQThe name of the shell function defined by the completion
        script.
        z\W* -r   )flagsZ_completion)resubr   replaceASCII)r$   	safe_namer   r   r   	func_name   s    zShellComplete.func_namec             C   s   | j | j| jdS )zVars for formatting :attr:`source_template`.

        By default this provides ``complete_func``, ``complete_var``,
        and ``prog_name``.
        )Zcomplete_funcr   r   )r<   r   r   )r$   r   r   r   source_vars   s    zShellComplete.source_varsc             C   s   | j |   S )zProduce the shell script that defines the completion
        function. By default this ``%``-style formats
        :attr:`source_template` with the dict returned by
        :meth:`source_vars`.
        )r3   r=   )r$   r   r   r   r      s    zShellComplete.sourcec             C   s   t dS )zUse the env vars defined by the shell script to return a
        tuple of ``args, incomplete``. This must be implemented by
        subclasses.
        N)NotImplementedError)r$   r   r   r   get_completion_args   s    z!ShellComplete.get_completion_args)args
incompleter   c             C   s0   t | j| j| j|}t|||\}}|||S )aT  Determine the context and last complete command or parameter
        from the complete args. Call that object's ``shell_complete``
        method to get the completions for the incomplete value.

        :param args: List of complete args before the incomplete value.
        :param incomplete: Value being completed. May be empty.
        )_resolve_contextr   r   r   _resolve_incompleter   )r$   r@   rA   ctxobjr   r   r   get_completions  s    
zShellComplete.get_completions)itemr   c             C   s   t dS )zFormat a completion item into the form recognized by the
        shell script. This must be implemented by subclasses.

        :param item: Completion item to format.
        N)r>   )r$   rG   r   r   r   format_completion  s    zShellComplete.format_completionc                s4      \}} ||} fdd|D }d|S )zProduce the completion data to send back to the shell.

        By default this calls :meth:`get_completion_args`, gets the
        completions, then calls :meth:`format_completion` for each
        completion.
        c                s   g | ]}  |qS r   )rH   ).0rG   )r$   r   r   
<listcomp>&  s    z*ShellComplete.complete.<locals>.<listcomp>
)r?   rF   join)r$   r@   rA   Zcompletionsoutr   )r$   r   r     s    zShellComplete.complete)r)   r*   r+   r,   r.   ZClassVarr0   __annotations__r   MutableMappingr/   r%   propertyr<   Dictr=   r   TupleListr?   r   rF   rH   r   r   r   r   r   r2      s"   

r2   c                   sn   e Zd ZdZdZeZeddddZe	d fddZ
ejeje	 e	f dd	d
Zee	dddZ  ZS )BashCompletezShell completion for Bash.bashN)r   c              C   s   dd l } dd l}| d}|d kr(d }n*|j|dddg|jd}td|j }|d k	r|	 \}}|dk s~|dkr|dk rt
td	d
d nt
tdd
d d S )Nr   rU   z--norcz-czecho "${BASH_VERSION}")stdoutz^(\d+)\.(\d+)\.\d+4zCShell completion is not supported for Bash versions older than 4.4.T)errz@Couldn't detect Bash version, shell completion is not supported.)shutil
subprocesswhichrunPIPEr7   searchrV   decodegroupsr   r   )rY   rZ   Zbash_exematchoutputmajorminorr   r   r   _check_version0  s&    



zBashComplete._check_versionc                s   |    t  S )N)re   superr   )r$   )	__class__r   r   r   Q  s    zBashComplete.sourcec             C   sV   t tjd }ttjd }|d| }y|| }W n tk
rL   d}Y nX ||fS )N
COMP_WORDS
COMP_CWORDr   r4   )r   osenvironint
IndexError)r$   cwordscwordr@   rA   r   r   r   r?   U  s    
z BashComplete.get_completion_args)rG   r   c             C   s   |j  d|j S )N,)r   r   )r$   rG   r   r   r   rH   a  s    zBashComplete.format_completion)r)   r*   r+   r,   r&   _SOURCE_BASHr3   staticmethodre   r0   r   r.   rR   rS   r?   r   rH   __classcell__r   r   )rg   r   rT   *  s    rT   c               @   sF   e Zd ZdZdZeZejej	e
 e
f dddZee
dddZd	S )
ZshCompletezShell completion for Zsh.zsh)r   c             C   sV   t tjd }ttjd }|d| }y|| }W n tk
rL   d}Y nX ||fS )Nrh   ri   r   r4   )r   rj   rk   rl   rm   )r$   rn   ro   r@   rA   r   r   r   r?   k  s    
zZshComplete.get_completion_args)rG   r   c             C   s$   |j  d|j d|jr|jnd S )NrK   r   )r   r   r    )r$   rG   r   r   r   rH   w  s    zZshComplete.format_completionN)r)   r*   r+   r,   r&   _SOURCE_ZSHr3   r.   rR   rS   r0   r?   r   rH   r   r   r   r   rt   e  s
   rt   c               @   sF   e Zd ZdZdZeZejej	e
 e
f dddZee
dddZd	S )
FishCompletezShell completion for Fish.fish)r   c             C   sH   t tjd }tjd }|dd  }|r@|r@|d |kr@|  ||fS )Nrh   ri   r   )r   rj   rk   pop)r$   rn   rA   r@   r   r   r   r?     s    
z FishComplete.get_completion_args)rG   r   c             C   s2   |j r |j d|j d|j  S |j d|j S )Nrp   	)r    r   r   )r$   rG   r   r   r   rH     s    zFishComplete.format_completionN)r)   r*   r+   r,   r&   _SOURCE_FISHr3   r.   rR   rS   r0   r?   r   rH   r   r   r   r   rw   {  s
   rw   ShellCompleteType)Zbound)rU   rx   ru   _available_shells)clsr&   r   c             C   s   |dkr| j }| t|< | S )am  Register a :class:`ShellComplete` subclass under the given name.
    The name will be provided by the completion instruction environment
    variable during completion.

    :param cls: The completion class that will handle completion for the
        shell.
    :param name: Name to register the class under. Defaults to the
        class's ``name`` attribute.
    N)r&   r~   )r   r&   r   r   r   add_completion_class  s    r   )r   r   c             C   s
   t | S )zLook up a registered :class:`ShellComplete` subclass by the name
    provided by the completion instruction environment variable. If the
    name isn't registered, returns ``None``.

    :param shell: Name the class is registered under.
    )r~   r'   )r   r   r   r   r     s    r   )rD   paramr   c             C   sl   t |tsdS |jdk	st| j|j}|jdkpj| |jtj	k	pj|jdkojt |t
tfojt||jk S )zDetermine if the given parameter is an argument that can still
    accept values.

    :param ctx: Invocation context for the command represented by the
        parsed complete args.
    :param param: Argument object being checked.
    FNry   r   )
isinstancer   r&   AssertionErrorparamsr'   nargsZget_parameter_sourcer
   ZCOMMANDLINEtuplelistlen)rD   r   r   r   r   r   _is_incomplete_argument  s    


r   )rD   r   r   c             C   s   |sdS |d }|| j kS )z5Check if the value looks like the start of an option.Fr   )Z_opt_prefixes)rD   r   cr   r   r   _start_of_option  s    r   )rD   r@   r   r   c             C   sl   t |tsdS |js|jrdS d}x6tt|D ]&\}}|d |jkrHP t| |r0|}q0W |dk	oj||jkS )zDetermine if the given parameter is an option that needs a value.

    :param args: List of complete args before the incomplete value.
    :param param: Option object being checked.
    FNr   )	r   r   Zis_flagcount	enumeratereversedr   r   opts)rD   r@   r   Zlast_optionindexargr   r   r   _is_incomplete_option  s    

r   )r   r   r   r@   r   c       	      C   s   d|d< | j || f|}|j|j }x|r|j}t|tr|js|||\}}}|dkrb|S |j |||dd}|j|j }q|}xB|r|||\}}}|dkr|S |j |||dddd}|j}qW |}|j|j}q*P q*W |S )a`  Produce the context hierarchy starting with the command and
    traversing the complete arguments. This only follows the commands,
    it doesn't trigger input prompts or callbacks.

    :param cli: Command being called.
    :param prog_name: Name of the executable in the shell.
    :param args: List of complete args before the incomplete value.
    Tresilient_parsingN)parentr   F)r   Zallow_extra_argsallow_interspersed_argsr   )	Zmake_contextcopyZprotected_argsr@   commandr   r   chainZresolve_command)	r   r   r   r@   rD   r   r&   cmdZsub_ctxr   r   r   rB     s:    

rB   )rD   r@   rA   r   c             C   s   |dkrd}n,d|kr:t | |r:|d\}}}|| d|krVt | |rV| j|fS | j| }x |D ]}t| ||rh||fS qhW x|D ]}t| |r||fS qW | j|fS )ah  Find the Click object that will handle the completion of the
    incomplete value. Return the object and the incomplete value.

    :param ctx: Invocation context for the command represented by
        the parsed complete args.
    :param args: List of complete args before the incomplete value.
    :param incomplete: Value being completed. May be empty.
    =r4   z--)r   r   appendr   
get_paramsr   r   )rD   r@   rA   r&   r   r   r   r   r   r   rC   /  s    




rC   )N)1rj   r7   typingr.   r   r   corer   r   r   r   r   r	   r
   parserr   utilsr   rO   r0   r/   rl   r   r   rq   rv   r|   r2   rT   rt   rw   ZTypeVarTyper}   r~   rQ   rN   r1   r   r   boolr   r   rS   r   rB   rR   UnionrC   r   r   r   r   <module>   sX     D,j; 
	5