U
    +c@                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlm	Z	 ddl
Z
d dd	Zd!d
dZd"ddZd#ddZd$ddZdd Zd%ddZdd Zd&ddZdd Zdd ZdS )'z?Provides tab completion functionality for CLIs built with Fire.    )absolute_import)division)print_functionN)inspectutilsbashc                 C   s(   |dkrt | t||S t| t||S )NZfish)_FishScript	_Commands_BashScript)name	componentdefault_optionsshell r   3/tmp/pip-unpacked-wheel-1xt1w7un/fire/completion.pyScript   s    r   c              	      s  |pt  }t ||\}}}d}d}d}dd fdd}	g }
t  }|  |t | }|t | }|D ]@}|	|jdt|| || d	}|
|j||d
 q|d|
}|j|d}|j  |d| 	dd	dd	ddd|dS )aX  Returns a Bash script registering a completion function for the commands.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    A string which is the Bash script. Source the bash script to enable tab
    completion in Bash.
  a  # bash completion support for {name}
# DO NOT EDIT.
# This script is autogenerated by fire/completion.py.

_complete-{identifier}()
{{
  local cur prev opts lastcommand
  COMPREPLY=()
  prev="${{COMP_WORDS[COMP_CWORD-1]}}"
  cur="${{COMP_WORDS[COMP_CWORD]}}"
  lastcommand=$(get_lastcommand)

  opts="{default_options}"
  GLOBAL_OPTIONS="{global_options}"

{checks}

  COMPREPLY=( $(compgen -W "${{opts}}" -- ${{cur}}) )
  return 0
}}

get_lastcommand()
{{
  local lastcommand i

  lastcommand=
  for ((i=0; i < ${{#COMP_WORDS[@]}}; ++i)); do
    if [[ ${{COMP_WORDS[i]}} != -* ]] && [[ -n ${{COMP_WORDS[i]}} ]] && [[
      ${{COMP_WORDS[i]}} != $cur ]]; then
      lastcommand=${{COMP_WORDS[i]}}
    fi
  done

  echo $lastcommand
}}

filter_options()
{{
  local opts
  opts=""
  for opt in "$@"
  do
    if ! option_already_entered $opt; then
      opts="$opts $opt"
    fi
  done

  echo $opts
}}

option_already_entered()
{{
  local opt
  for opt in ${{COMP_WORDS[@]:0:COMP_CWORD}}
  do
    if [ $1 == $opt ]; then
      return 0
    fi
  done
  return 1
}}

is_prev_global()
{{
  local opt
  for opt in $GLOBAL_OPTIONS
  do
    if [ $opt == $prev ]; then
      return 0
    fi
  done
  return 1
}}

complete -F _complete-{identifier} {command}
z;
  case "${{lastcommand}}" in
  {lastcommand_checks}
  esaczQ
    {command})
      {opts_assignment}
      opts=$(filter_options $opts)
    ;;z
      if is_prev_global; then
        opts="${{GLOBAL_OPTIONS}}"
      else
        opts="{options} ${{GLOBAL_OPTIONS}}"
      fiz,
      opts="{options} ${{GLOBAL_OPTIONS}}" c                    s   |  krS S d S Nr   )commandr
   Z%opts_assignment_main_command_templateZ#opts_assignment_subcommand_templater   r   _GetOptsAssignmentTemplate   s    z/_BashScript.<locals>._GetOptsAssignmentTemplate )options)r   opts_assignment
)lastcommand_checks/ .,)r
   r   checksr   
identifierglobal_options)
set_GetMapsaddunionkeysformatjoinsortedappendreplace)r
   commandsr   r    options_mapsubcommands_mapZbash_completion_templateZcheck_wrapperZlastcommand_check_templater   linesZcommands_setr   r   r   r   r   r   r   r	   #   sT    
  
M

r	   c              
   C   s   |pt  }t| ||\}}}d}d}d}d}	t | t | D ]f}
||
 D ]}||j| |
|d7 }qR||
 |D ]0}|
| k}||j| |
|r|	nd|dd7 }qzqF|jd	d
d |D dS )aX  Returns a Fish script registering a completion function for the commands.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    A string which is the Fish script. Source the fish script to enable tab
    completion in Fish.
  aL  function __fish_using_command
    set cmd (commandline -opc)
    for i in (seq (count $cmd) 1)
        switch $cmd[$i]
        case "-*"
        case "*"
            if [ $cmd[$i] = $argv[1] ]
                return 0
            else
                return 1
            end
        end
    end
    return 1
end

function __option_entered_check
    set cmd (commandline -opc)
    for i in (seq (count $cmd))
        switch $cmd[$i]
        case "-*"
            if [ $cmd[$i] = $argv[1] ]
                return 1
            end
        end
    end
    return 0
end

function __is_prev_global
    set cmd (commandline -opc)
    set global_options {global_options}
    set prev (count $cmd)

    for opt in $global_options
        if [ "--$opt" = $cmd[$prev] ]
            echo $prev
            return 0
        end
    end
    return 1
end

zJcomplete -c {name} -n '__fish_using_command {command}' -f -a {subcommand}
z}complete -c {name} -n '__fish_using_command {command};{prev_global_check} and __option_entered_check --{option}' -l {option}
z and __is_prev_global;)r
   r   
subcommandr   z--)r
   r   prev_global_checkoptionr   c                 s   s   | ]}d j |dV  qdS )z
"{option}")r1   N)r&   ).0r1   r   r   r   	<genexpr>  s   z_FishScript.<locals>.<genexpr>)r    )r!   r"   r%   r$   r&   lstripr'   )r
   r+   r   r    r,   r-   Zfish_sourceZsubcommand_templateZflag_templater0   r   r/   r1   Zcheck_neededr   r   r   r      s<    
  
-


r   Fc                 C   s$  t |tjr|drdS |r"dS |tks:|tks:|tkr>dS t |ttrVtjrVdS t	
|rl|tkrldS t	| r|dkrt|pi }||}|r|jdkrdS ttdtd}t |j|rdS tjrt	| r|dkrdS tjrt	| r|dkrdS t |tjr |d	 S dS )
a  Returns whether a member should be included in auto-completion or help.

  Determines whether a member of an object with the specified name should be
  included in auto-completion or help text(both usage and detailed help).

  If the member name starts with '__', it will always be excluded. If it
  starts with only one '_', it will be included for all non-string types. If
  verbose is True, the members, including the private members, are included.

  When not in verbose mode, some modules and functions are excluded as well.

  Args:
    component: The component containing the member.
    name: The name of the member.
    member: The member itself.
    class_attrs: (optional) If component is a class, provide this as:
      inspectutils.GetClassAttrsDict(component). If not provided, it will be
      computed.
    verbose: Whether to include private members.
  Returns
    A boolean value indicating whether the member should be included.
  __FTN)methodproperty_tuplegetter)Zfunc_closure	func_codeZfunc_defaultsZ	func_dictZfunc_docZfunc_globals	func_name)Zim_classZim_funcZim_self_)
isinstancesixstring_types
startswithr   r   r   typePY34inspectismoduleisclassr   GetClassAttrsDictgetkindgetattrcollectionsobjectPY2
isfunctionismethod)r   r
   memberclass_attrsverboseZ
class_attrZtuplegetterr   r   r   MemberVisible   sF    


rQ   c                    sF   t tr }n
t} dkr0t  fdd|D S )a  Returns a list of the members of the given component.

  If verbose is True, then members starting with _ (normally ignored) are
  included.

  Args:
    component: The component whose members to list.
    class_attrs: (optional) If component is a class, you may provide this as:
      inspectutils.GetClassAttrsDict(component). If not provided, it will be
      computed. If provided, this determines how class members will be treated
      for visibility. In particular, methods are generally hidden for
      non-instantiated classes, but if you wish them to be shown (e.g. for
      completion scripts) then pass in a different class_attr for them.
    verbose: Whether to include private members.
  Returns:
    A list of tuples (member_name, member) of all members of the component.
  Nc              	      s*   g | ]"\}}t || d r||fqS )rO   rP   )rQ   )r2   member_namerN   rO   r   rP   r   r   
<listcomp>y  s
   
z"VisibleMembers.<locals>.<listcomp>)r<   dictitemsrB   
getmembersr   rE   )r   rO   rP   membersr   rT   r   VisibleMembers_  s    



rZ   c                 C   s0   g }| D ]"}| dd}|dj|d q|S )zTakes a list of fn args and returns a list of the fn's completion strings.

  Args:
    fn_args: A list of the args accepted by a function.
  Returns:
    A list of possible completion strings for that function.
  r;   -z--{arg}arg)r*   r)   r&   )Zfn_argsZcompletionsr]   r   r   r   _CompletionsFromArgs  s
    r^   c                 C   sv   t | st | r.t| }t|j|j S t| t	t
frRdd tt| D S t | r`g S dd t| |dD S )a  Gives possible Fire command completions for the component.

  A completion is a string that can be appended to a command to continue that
  command. These are used for TAB-completions in Bash for Fire CLIs.

  Args:
    component: The component whose completions to list.
    verbose: Whether to include all completions, even private members.
  Returns:
    A list of completions for a command that would so far return the component.
  c                 S   s   g | ]}t |qS r   )str)r2   indexr   r   r   rU     s     zCompletions.<locals>.<listcomp>c                 S   s   g | ]\}}t |qS r   )_FormatForCommand)r2   rS   r;   r   r   r   rU     s   rP   )rB   	isroutinerD   r   ZGetFullArgSpecr^   args
kwonlyargsr<   tuplelistrangelenisgeneratorrZ   )r   rP   specr   r   r   Completions  s    


rl   c                 C   s.   t | tjst| } | dr"| S | ddS )a  Replaces underscores with hyphens, unless the token starts with a token.

  This is because we typically prefer hyphens to underscores at the command
  line, but we reserve hyphens at the start of a token for flags. This becomes
  relevant when --verbose is activated, so that things like __str__ don't get
  transformed into --str--, which would get confused for a flag.

  Args:
    token: The token to transform.
  Returns:
    The transformed token.
  r;   r[   )r<   r=   r>   r_   r?   r*   )tokenr   r   r   ra     s
    
ra      c                 c   s   t | st | r.t| ddD ]}|fV  q t | r<dS |dk rHdS t| i ddD ]8\}}t|}|fV  t||d D ]}|f| V  q|qVdS )a	  Yields tuples representing commands.

  To use the command from Python, insert '.' between each element of the tuple.
  To use the command from the command line, insert ' ' between each element of
  the tuple.

  Args:
    component: The component considered to be the root of the yielded commands.
    depth: The maximum depth with which to traverse the member DAG for commands.
  Yields:
    Tuples, each tuple representing one possible command for this CLI.
    Only traverses the member DAG up to a depth of depth.
  Frb   N   rR   )rB   rc   rD   rl   rZ   ra   r   )r   depth
completionrS   rN   r   r   r   r   r     s    

r   c                 C   s
   |  dS )Nr[   )r?   r\   r   r   r   	_IsOption  s    rr   c           
         s   t   }t fdd}tt}|D ]}t|dkrjt|d rV||d  q||  |d  q*|r*|d }t|d }t|r|}	n|}	|	| | |	|dd | q*|||fS )	a  Returns sets of subcommands and options for each command.

  Args:
    name: The first token in the commands, also the name of the command.
    commands: A list of all possible commands that tab completion can complete
        to. Each command is a list or tuple of the string tokens that make up
        that command.
    default_options: A dict of options that can be used with any command. Use
        this if there are flags that can always be appended to a command.
  Returns:
    global_options: A set of all options of the first token of the command.
    subcommands_map: A dict storing set of subcommands for each
        command/subcommand.
    options_map: A dict storing set of options for each subcommand.
  c                      s
   t   S r   )copyr   r   r   r   <lambda>      z_GetMaps.<locals>.<lambda>ro   r   r;   r[   )	rs   rI   defaultdictr!   ri   rr   r#   ra   r*   )
r
   r+   r   r    r,   r-   r   r/   r]   Zargs_mapr   rt   r   r"     s"    

r"   )Nr   )N)N)NF)NF)F)rn   )__doc__
__future__r   r   r   rI   rs   rB   Zfirer   r=   r   r	   r   rQ   rZ   r^   rl   ra   r   rr   r"   r   r   r   r   <module>   s(   

 
`
?
!

#