3
¦YðiSF  ã               @   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eedœZejeej e f d3ej e ej!e ddœdd „Z"eej!ej e  d!œd"d#„Z#e	ee$d$œd%d&„Z%ee$d'œd(d)„Z&ej'e ee$d*œd+d,„Z(eejeejf eej'e e	d-œd.d/„Z)e	ej'e eej*ej+eef ef d0œd1d2„Z,dS )4é    N)Úgettexté   )ÚArgument)ÚBaseCommand)ÚContext)ÚMultiCommand)ÚOption)Ú	Parameter)ÚParameterSource)Úsplit_arg_string)Úecho)ÚcliÚctx_argsÚ	prog_nameÚcomplete_varÚinstructionÚreturnc       	      C   sf   |j dƒ\}}}t|ƒ}|dkr$dS || |||ƒ}|dkrJt|jƒ ƒ dS |dkrbt|jƒ ƒ 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   ú7/tmp/pip-build-8om4l6ph/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 j|ƒS )N)r!   Úget)r$   r&   r   r   r   Ú__getattr__X   s    zCompletionItem.__getattr__)r   r   r    r!   )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
}

compdef %(complete_func)s %(prog_name)s;
a©  function %(complete_func)s;
    set -l response;

    for value in (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) %(prog_name)s);
        set response $response $value;
    end;

    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je 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
    N)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jddƒt jƒ}d|› d�S )zQThe name of the shell function defined by the completion
        script.
        z\W*Ú ú-r   Z_completion)ÚreÚsubr   ÚreplaceÚASCII)r$   Ú	safe_namer   r   r   Ú	func_nameâ   s    zShellComplete.func_namec             C   s   | j | j| jdœS )z—Vars 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 | jƒ  S )zÊProduce the shell script that defines the completion
        function. By default this ``%``-style formats
        :attr:`source_template` with the dict returned by
        :meth:`source_vars`.
        )Úsource_templater;   )r$   r   r   r   r   ö   s    zShellComplete.sourcec             C   s   t ‚dS )z˜Use 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|||ƒ\}}|j||ƒ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?   r@   ÚctxÚobjr   r   r   Úget_completions  s    
zShellComplete.get_completions)Úitemr   c             C   s   t ‚dS )z°Format 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$   rF   r   r   r   Úformat_completion  s    zShellComplete.format_completionc                s4   ˆ j ƒ \}}ˆ j||ƒ}‡ fdd„|D ƒ}dj|ƒS )zÛProduce 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 | ]}ˆ j |ƒ‘qS r   )rG   )Ú.0rF   )r$   r   r   ú
<listcomp>$  s    z*ShellComplete.complete.<locals>.<listcomp>Ú
)r>   rE   Újoin)r$   r?   r@   ZcompletionsÚoutr   )r$   r   r     s    zShellComplete.complete)r)   r*   r+   r,   r.   ZClassVarr0   r&   r<   r   ÚDictr/   r%   Úpropertyr:   r;   r   ÚTupleÚListr>   r   rE   rG   r   r   r   r   r   r2   ¾   s"   



r2   c                   sj   e Zd ZdZdZeZ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   sz   dd l }|jdddg|jd�}tjd|jjƒ ƒ}|d k	rj|jƒ \}}|dk s\|dkrv|dk rvtt	dƒƒ‚ntt	d	ƒƒ‚d S )
Nr   rR   z-czecho ${BASH_VERSION})Ústdoutz^(\d+)\.(\d+)\.\d+Ú4zCShell completion is not supported for Bash versions older than 4.4.z@Couldn't detect Bash version, shell completion is not supported.)
Ú
subprocessÚrunÚPIPEr5   ÚsearchrS   ÚdecodeÚgroupsÚRuntimeErrorr   )r$   rU   ÚoutputÚmatchÚmajorÚminorr   r   r   Ú_check_version.  s    
zBashComplete._check_versionc                s   | j ƒ  tƒ jƒ S )N)r`   Úsuperr   )r$   )Ú	__class__r   r   r   E  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   r3   )r   ÚosÚenvironÚintÚ
IndexError)r$   ÚcwordsÚcwordr?   r@   r   r   r   r>   I  s    
z BashComplete.get_completion_args)rF   r   c             C   s   |j › d|j› �S )Nú,)r   r   )r$   rF   r   r   r   rG   U  s    zBashComplete.format_completion)r)   r*   r+   r,   r&   Ú_SOURCE_BASHr<   r`   r0   r   r.   rO   rP   r>   r   rG   Ú__classcell__r   r   )rb   r   rQ   (  s   rQ   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 )Nrc   rd   r   r3   )r   re   rf   rg   rh   )r$   ri   rj   r?   r@   r   r   r   r>   _  s    
zZshComplete.get_completion_args)rF   r   c             C   s$   |j › d|j› d|jr|jnd› �S )NrJ   r   )r   r   r    )r$   rF   r   r   r   rG   k  s    zZshComplete.format_completionN)r)   r*   r+   r,   r&   Ú_SOURCE_ZSHr<   r.   rO   rP   r0   r>   r   rG   r   r   r   r   rn   Y  s
   rn   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@|jƒ  ||fS )Nrc   rd   r   éÿÿÿÿ)r   re   rf   Úpop)r$   ri   r@   r?   r   r   r   r>   u  s    
z FishComplete.get_completion_args)rF   r   c             C   s2   |j r |j› d|j› d|j › �S |j› d|j› �S )Nrk   ú	)r    r   r   )r$   rF   r   r   r   rG   �  s    zFishComplete.format_completionN)r)   r*   r+   r,   r&   Ú_SOURCE_FISHr<   r.   rO   rP   r0   r>   r   rG   r   r   r   r   rq   o  s
   rq   )rR   rr   ro   )Úclsr&   r   c             C   s   |dkr| j }| t|< d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&   Ú_available_shells)rw   r&   r   r   r   Úadd_completion_class�  s    ry   )r   r   c             C   s
   t j| ƒS )zñLook 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.
    )rx   r'   )r   r   r   r   r   ¡  s    r   )rC   Úparamr   c             C   sj   t |tƒsdS |jdk	st‚| j|j }|jdkph| j|jƒtjk	ph|jdkoht |t	t
fƒoht|ƒ|jk S )zìDetermine 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.
    FNr   rs   )Ú
isinstancer   r&   ÚAssertionErrorÚparamsÚnargsZget_parameter_sourcer
   ZCOMMANDLINEÚtupleÚlistÚlen)rC   rz   r   r   r   r   Ú_is_incomplete_argument«  s    


r‚   )r   r   c             C   s"   | sdS | d }|j ƒ  o |dkS )z5Check if the value looks like the start of an option.Fr   ú/)Úisalnum)r   Úcr   r   r   Ú_start_of_optionÃ  s    r†   )r?   rz   r   c             C   sd   t |tƒsdS |jrdS d}x4tt| ƒƒD ]$\}}|d |jkrBP t|ƒr*|}q*W |dk	ob||jkS )zºDetermine 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Ú	enumerateÚreversedr~   r†   Úopts)r?   rz   Zlast_optionÚindexÚargr   r   r   Ú_is_incomplete_optionÍ  s    
rŒ   )r   r   r   r?   r   c       	      C   sâ   d|d< | j ||jƒ f|Ž}|j|j }x´|rÜ|j}t|tƒrØ|js‚|j||ƒ\}}}|dkrb|S |j |||dd�}|j|j }qÚxB|rÄ|j||ƒ\}}}|dkr¦|S |j |||dddd�}|j}q„W |}|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?   rC   r‘   r&   ÚcmdZsub_ctxr   r   r   rA   å  s8    

rA   )rC   r?   r@   r   c             C   s¨   |dkrd}n*d|kr8t |ƒr8|jdƒ\}}}|j|ƒ d|krRt |ƒrR| j|fS | jj| ƒ}x|D ]}t||ƒrd||fS qdW x|D ]}t| |ƒr„||fS q„W | 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.
    ú=r3   z--)r†   r   Úappendr‘   Ú
get_paramsrŒ   r‚   )rC   r?   r@   r&   r   r}   rz   r   r   r   rB     s    





rB   )N)-re   r5   Útypingr.   r   r   Úcorer   r   r   r   r   r	   r
   Úparserr   Úutilsr   rM   r0   r/   rg   r   r   rl   rp   rv   r2   rQ   rn   rq   rx   ÚTyper1   ry   r   Úboolr‚   r†   rP   rŒ   rA   rO   ÚUnionrB   r   r   r   r   Ú<module>   sP     D&j1

3