
    *                         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 Zd Zd Zd Zd Zd Zy) 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                 0   t        j                  t              }| s|S d}t        t	        j
                  |       d      dd }|D ]  }t        j                  j                  | |      }t        j                  |      5 }|D ]L  }t        j                  t        j                  |      }|s*|j                  d      }	|dz  }||	xx   dz  cc<   N 	 ddd        t        j                   |      D 	
ci c]  \  }	}
|	|
|z   c}
}	S # 1 sw Y   xY wc c}
}	w )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      )collectionsdefaultdictintsortedoslistdirpathjoinr   
FileReaderresearchr   USED_SURFACE_PATTERNgroupsix	iteritems)logs_dirsurfaces_counttotallast_100_invocationsfilename	file_pathlog_filelinematchsurfacecounts              /lib/googlecloudsdk/calliope/suggest_commands.py_GetSurfaceHistoryFrequenciesr<   ;   s     **3/.	
%

8 4dCDSI&hXx0I			)	$$		#22D9KKN'
1*%

!Q
&
!  
%	$ ' 47==3P
3P%guu}3P
  
%	$
s   =,D*%D2DD	c                 $   | j                  t        j                        s|j                  |dd        yt	        j
                  | t        j                           D ]3  \  }}|j                  |       t        |||       |j                          5 y)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appendr.   r/   _GetCanonicalCommandsHelperpop)treeresultsprefixcommandcommand_trees        r;   r@   r@   X   sn     
&((	)NN6!9
"}}T&2H2H-IJg|
MM'gv>
JJL  K    c                 &    g }t        | |g        |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.
  )rD   )r@   )rB   rC   s     r;   _GetCanonicalCommandsrI   n   s     'dGB7	.rG   c                    d}||v r|}|}n||v r|}|}n|S |j                  |      }|dkD  r||dz
     dk7  r|S |dz  }|dk(  r|dz  }n|dk(  r|dz  }n
|dk(  r|dz  }| dk(  r|d	z  }n| dk(  r|d
z  }n|dz  }t        |      t        |      z
  }|dk  r d|z
  }|j                  |      r|dz  }||z  }| dk(  r|dkD  r|dz  }|S | dkD  r|| dz   kD  r|d
z  }|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extras	            r;   
_WordScorer_   }   sY   " %  66*L(K!88)L)KL 	&#1WS1W%,L 2+% "	RKE1$	RKE1$	RKE aZ	RKEz	RKE	QJE k
S.
.%
aZIEl+qje	UNE aZ,q0	RKE
 
, qy-	9	RKE	,rG   c           	         t        j                         }t        t        j                               }| D cg c]"  }|j                         j                  dd      $ }}g }t        |      }t        t        t        |            }|D ]F  }t        |      }	t               }
d}t        |      D ]_  \  }}|D ]U  }t        ||||	      }t        j                  |      }|rt        ||||	      }||k  r|}|s@|
j!                  |       ||z  }W a t        |
      t        |      k(  r|dz  }|dkD  sdj#                  |dd       }||v r|t%        ||   t&        z        z  }d}d	|d   k(  r-|d
z  }t        |dd       |v rd}t        dg|dd z         |v rd}d|d   k(  r|d
z  }t        |dd       |v rd}|r4|j)                  ||f       I |j+                  d        |S c c}w )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.
  _rK   r   r   .NFalpharR   r    Tbetac                     | d    | d   fS )Nr    r    )tuples    r;   <lambda>z._GetScoredCommandsContaining.<locals>.<lambda>  s    58)U1X)>rG   )key)r   LoadCompletionCliTreer<   r   	GetLogDirlowerreplacerI   setmaprh   rT   	enumerater_   SYNONYMSr   r   r(   r#   FREQUENCY_FACTORr?   sort)command_wordsrootsurface_historycommand_wordnormalized_command_wordsscored_commandsall_canonical_commandscanonical_command_setcanonical_command_wordsrY   matchedrZ   rV   rX   rW   	incrementalternate_command_wordalternate_incrementr9   better_track_existss                       r;   _GetScoredCommandsContainingr      sT    
	%	%	'$1#--/B/ANANl""3,   /06c%)?@A!7"#:;eGE)23J)K%%%=
!#"$	
	 "*.E!F! *$$&	!
 ,,+I
++-
.
9
%) &> *L0 7|s344rkeqy0"56g	O	#_W-0@@AA "	+A.	.
(,-1FF $
6(4QR889$% !%
	*1-	-
(,-1FF $
  7?@k "8p >?	s   'G&c           	         g }	 t        |       }|s|S t        |d   d         }d}t	               }|D ]o  \  }}||z  t
        k\  s|j                  dj                  dg|z                |j                  dj                  |dd              t        |      t        k\  smd} n |rt        |      t        k  rt        |d   d         }|D ]-  \  }}||z  t
        k  r n|t        |      kD  s#t        |      }/ |dz
  }	|	rht	               }|D ]N  \  }}||z  t
        k  r n=|j                  dj                  dg|d|	 z                t        |      t        k\  sN n t        |      }|S # t        j                  $ r d}Y uw xY w)	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 gcloudrc   T)r   r   CannotHandleCompletionErrorfloatro   	MIN_RATIOr?   r(   r   rT   MAX_SUGGESTIONSMIN_SUGGESTED_GROUPSr$   )
ru   suggested_commandsrz   	top_scoretoo_manysuggested_groupsrE   rZ   
min_lengthcommon_lengths
             r;   GetCommandSuggestionsr     s    2=AO 
 OA&q)*)(U'nguyI%(g)= >?388GCRL12		 O	3 ( #&'*>>_Q'*+J)		Y	&	c'l	"\
	 *
 NM+.'59y(
SXXxj7>M3J&JKL O3
 , ""23	K 
	+	+ Os   E, ,FF)__doc__
__future__r   r   r   r!   r%   r*   ,googlecloudsdk.command_lib.static_completionr   googlecloudsdk.corer   googlecloudsdk.core.utilr   r.   rr   r   r   r   rs   r<   r@   rI   r_   r   r   rg   rG   r;   <module>r      s     ; &  '  	 	 ? # * 

 %$ 	   :,EPM`5rG   