o
    *                     @   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
mZ ddlmZ ddlZd	d
dddddddddd	d	dddZdZdZdZdZdd Zdd Zdd Zd d! Zd"d# Zd$d% ZdS )&z4Methods for suggesting corrections to command typos.    )absolute_import)division)unicode_literalsN)lookup)log)filesupdatescpaddremovegetzauth-configure-dockerdescribeimages	instancesinstancecreatedelete)changez
copy-filesr   r   r   dockerr   imager   r   makemodifypatchr   showgffffff?   
   d   c           	   	      s   t t}| s	|S d tt| dddd }|D ]=}tj| |}t	|'}|D ]}t
tj|}|rG|d} d7  ||  d7  < q+W d   n1 sRw   Y  q fddt|D S )	zLoad the last 100 surfaces user used today from local command history.

  Args:
    logs_dir: str, the path to today's logs directory

  Returns:
    dict mapping surfaces to normalized frequencies.
  r   T)reverseNr      c                    s   i | ]	\}}||  qS  r   ).0surfacecounttotalr   E/tmp/google-cloud-sdk/lib/googlecloudsdk/calliope/suggest_commands.py
<dictcomp>S   s    z1_GetSurfaceHistoryFrequencies.<locals>.<dictcomp>)collectionsdefaultdictintsortedoslistdirpathjoinr   
FileReaderresearchr   USED_SURFACE_PATTERNgroupsix	iteritems)	logs_dirsurfaces_countlast_100_invocationsfilename	file_pathlog_filelinematchr!   r   r#   r%   _GetSurfaceHistoryFrequencies;   s*   
	

r>   c                 C   s^   |  tjs||dd  dS t| tj D ]\}}|| t||| |  qdS )af  Helper method to _GetCanonicalCommands.

  Args:
    tree: The root of the tree that will be traversed to find commands.
    results: The results list to append to.
    prefix: [str], the canonical command line words so far. Once we reach a leaf
      node, prefix contains a canonical command and a copy is appended to
      results.

  Returns:
    None
  N)r   r   LOOKUP_COMMANDSappendr4   r5   _GetCanonicalCommandsHelperpop)treeresultsprefixcommandcommand_treer   r   r%   rA   X   s   

rA   c                 C   s   g }t | |g d |S )a  Return list of all canonical commands in CLI tree in arbitrary order.

  Args:
    tree: The root of the tree that will be traversed to find commands.

  Returns:
    [[canonical_command_words]]: List of lists, all possible sequences of
      canonical command words in the tree.
  )rE   )rA   )rC   rD   r   r   r%   _GetCanonicalCommandsn   s   
rH   c           	      C   s0  d}||v r|}|}n||v r|}|}n|S | |}|dkr)||d  dkr)|S |d7 }|dkr6|d7 }n|dkr?|d7 }n|dkrG|d7 }| dkrP|d	7 }n| dkrY|d
7 }n|d7 }t|t| }|dkrzd| }||rv|d9 }||7 }| dkr|dkr|d7 }|S | dkr|| d kr|d
7 }|S )ar  Returns the integer word match score for a command word.

  Args:
    index: The position of the word in the command.
    normalized_command_word: The normalized command word.
    canonical_command_word: The actual command word to compare with.
    canonical_command_length: The length of the actual command.

  Returns:
    The integer word match score, always >= 0.
  r   r   -r                        )findlen
startswith)	indexnormalized_command_wordcanonical_command_wordcanonical_command_lengthscoreshorter_wordlonger_wordhitextrar   r   r%   
_WordScore}   sF   





r]   c                 C   s  t  }tt }dd | D }g }t|}ttt|}|D ]}t	|}t }	d}
t
|D ]/\}}|D ](}t||||}t|}|rRt||||}||k rR|}|r]|	| |
|7 }
q5q/t	|	t	|krk|
d7 }
|
dkrd|dd }||v r|
t|| t 7 }
d}d	|d kr|
d
8 }
t|dd |v rd}tdg|dd  |v rd}d|d kr|
d
8 }
t|dd |v rd}|s|||
f q |jdd d |S )a  Return scored canonical commands containing input command words.

  Args:
    command_words: List of input command words.

  Returns:
    [(canonical_command_words, score)]: List of tuples, where
      canonical_command_words is a list of strings and score is an integer > 0.
      The tuples are sorted from highest score to lowest, and commands with
      the same score appear in lexicographic order.
  c                 S   s   g | ]
}|  d dqS )_rI   )lowerreplace)r    command_wordr   r   r%   
<listcomp>   s    z0_GetScoredCommandsContaining.<locals>.<listcomp>r   r   .NFalpharP   r   Tbetac                 S   s   | d  | d fS )Nr   r   r   )tupler   r   r%   <lambda>  s    z._GetScoredCommandsContaining.<locals>.<lambda>)key)r   LoadCompletionCliTreer>   r   	GetLogDirrH   setmaprg   rR   	enumerater]   SYNONYMSr   r
   r.   r)   FREQUENCY_FACTORr@   sort)command_wordsrootsurface_historynormalized_command_wordsscored_commandsall_canonical_commandscanonical_command_setcanonical_command_wordsrW   matchedrX   rT   rV   rU   	incrementalternate_command_wordalternate_incrementr!   better_track_existsr   r   r%   _GetScoredCommandsContaining   sv   

r   c           
   	   C   sd  g }zt | }W n tjy   d}Y nw |s|S t|d d }d}t }|D ]+\}}|| tkrS|ddg|  |d|dd  t	|t
krSd} nq(|rt	|tk rt	|d d }|D ]\}}|| tk rr n|t	|kr|t	|}qf|d }	|	rt }|D ]#\}}|| tk r n|ddg|d|	   t	|t
kr nqt|}|S )	a  Return suggested commands containing input command words.

  Args:
    command_words: List of input command words.

  Returns:
    [command]: A list of canonical command strings with 'gcloud' prepended. Only
      commands whose scores have a ratio of at least MIN_RATIO against the top
      score are returned. At most MAX_SUGGESTIONS command strings are returned.
      If many commands from the same group are being suggested, then the common
      groups are suggested instead.
  Nr   r   F gcloudrd   T)r   r   CannotHandleCompletionErrorfloatrl   	MIN_RATIOr@   r.   r
   rR   MAX_SUGGESTIONSMIN_SUGGESTED_GROUPSr*   )
rr   suggested_commandsrv   	top_scoretoo_manysuggested_groupsrF   rX   
min_lengthcommon_lengthr   r   r%   GetCommandSuggestions  sN   r   )__doc__
__future__r   r   r   r'   r+   r0   ,googlecloudsdk.command_lib.static_completionr   googlecloudsdk.corer   googlecloudsdk.core.utilr   r4   ro   r   r   r   rp   r>   rA   rH   r]   r   r   r   r   r   r%   <module>   sJ   HP