
    +                        d Z ddlm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	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ZdZdj1                         Z G d de      Z G d de      Z G d de      Z G d de      Z G d dej>                        Z  G d de!      Z" G d de      Z# G d d e      Z$ G d! d"e      Z%d# Z&d$ Z'y)%zShell tab completion.    )absolute_import)print_function)division)unicode_literalsN)CannedACLStrings)IsFileUrlString)StorageUrlFromString)StripOneSlash)GetTabCompletionCacheFilename)GetTabCompletionLogFilename)CreateWildcardIterator   i  z
Tab completion aborted (took >%ss), you may complete the command manually.
The timeout can be adjusted in the gsutil configuration file.
c                   $    e Zd ZdZdZdZdZdZdZy)CompleterTypecloud_bucketcloud_objectcloud_or_local_objectlocal_objectlocal_object_or_canned_aclno_opN)	__name__
__module____qualname__CLOUD_BUCKETCLOUD_OBJECTCLOUD_OR_LOCAL_OBJECTLOCAL_OBJECTLOCAL_OBJECT_OR_CANNED_ACLNO_OP     %platform/gsutil/gslib/tab_complete.pyr   r   /   s"    ,,1,;
%r!   r   c                       e Zd ZdZd Zd Zy)LocalObjectCompleterz!Completer object for local files.c                 (    ddl m}  |       | _        y )Nr   )FilesCompleter)argcomplete.completersr&   files_completer)selfr&   s     r"   __init__zLocalObjectCompleter.__init__;   s     6)+Dr!   c                 (     | j                   |fi |S N)r(   )r)   prefixkwargss      r"   __call__zLocalObjectCompleter.__call__B   s    41&11r!   Nr   r   r   __doc__r*   r/   r    r!   r"   r$   r$   8   s    ),2r!   r$   c                       e Zd ZdZd Zd Zy)LocalObjectOrCannedACLCompleterz|Completer object for local files and canned ACLs.

  Currently, only Google Cloud Storage canned ACL names are supported.
  c                 "    t               | _        y r,   )r$   local_object_completer)r)   s    r"   r*   z(LocalObjectOrCannedACLCompleter.__init__L   s    "6"8Dr!   c                      | j                   |fi |}t        D cg c]  }|j                  |      s| }}||z   S c c}w r,   )r5   r   
startswith)r)   r-   r.   local_objectsaclcanned_aclss         r"   r/   z(LocalObjectOrCannedACLCompleter.__call__O   sK    /D//A&AM"2M"23cnnV6L3"2KM;&& Ns   >>Nr0   r    r!   r"   r3   r3   F   s    
9'r!   r3   c                   8    e Zd ZdZd Zed        Zd Zd Zd Z	y)TabCompletionCachez!Cache for tab completion results.c                 <    || _         || _        || _        || _        y r,   )r-   results	timestamppartial_results)r)   r-   r>   r?   r@   s        r"   r*   zTabCompletionCache.__init__X   s    DKDLDN*Dr!   c                     	 t        | d      5 }t        j                  |j                               }|d   }|d   }|d   }|d   }ddd       t              S # 1 sw Y   xY w# t        $ r d}g }d}d}Y -w xY w)	zInstantiates the cache from a file.

    Args:
      filename: The file to load.
    Returns:
      TabCompletionCache instance with loaded data or an empty cache
          if the file cannot be loaded
    rr-   r>   r?   partial-resultsNr   F)openjsonloadsread	Exceptionr<   )filenamefp
cache_dictr-   r>   r?   r@   s          r"   LoadFromFilezTabCompletionCache.LoadFromFile^   s    #"ZZ	*
H%Y'{+	$%67  fgy/JJ    fgios(   A( 8AA( A%!A( (A<;A<c                    t        j                          }|| j                  z
  t        k\  ryd}|| j                  k(  r| j                  }n| j
                  ss|j                  | j                        rX|j                  d      | j                  j                  d      k(  r+| j                  D cg c]  }|j                  |      s| }}|t        j                          | _        |S yc c}w )z>Returns the cached results for prefix or None if not in cache.N/)timer?   TAB_COMPLETE_CACHE_TTLr-   r>   r@   r7   count)r)   r-   current_timer>   xs        r"   GetCachedResultsz#TabCompletionCache.GetCachedResultsz   s    99;Ldnn$(>>Gg""v'8'8'E
,,s
t{{005
5 LLALqALL,@LgA
 yy{dnn  Bs   ,C'C'c                 `    || _         || _        || _        t        j                         | _        y)zBUpdates the in-memory cache with the results for the given prefix.N)r-   r>   r@   rO   r?   )r)   r-   r>   r@   s       r"   UpdateCachezTabCompletionCache.UpdateCache   s%    DKDL*DYY[DNr!   c                    t        j                  | j                  | j                  | j                  | j
                  d      }	 t        |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)z'Writes out the cache to the given file.)r-   r>   rC   r?   wN)	rE   dumpsr-   r>   r@   r?   rD   writeIOError)r)   rI   json_strrJ   s       r"   WriteToFilezTabCompletionCache.WriteToFile   sm    zz++<<//^^	 H#"
  
s0   A7 A+"A7 +A40A7 4A7 7	BBN)
r   r   r   r1   r*   staticmethodrL   rT   rV   r]   r    r!   r"   r<   r<   U   s/    )+ K K6,!r!   r<   c                   (     e Zd ZdZ fdZd Z xZS )CloudListingRequestThreadz@Thread that performs a listing request for the given URL string.c                 b    t         t        |           d| _        || _        || _        d| _        y)zInstantiates Cloud listing request thread.

    Args:
      wildcard_url_str: The URL to list.
      gsutil_api: gsutil Cloud API instance to use.
    TN)superr`   r*   daemon_wildcard_url_str_gsutil_apir>   )r)   wildcard_url_str
gsutil_api	__class__s      r"   r*   z"CloudListingRequestThread.__init__   s1     

#T35DK-D!DDLr!   c                     t        | j                  | j                        j                  dg      }t	        j
                  |t              D cg c]  }t        |       c}| _        y c c}w )Nname)bucket_listing_fields)	r   rd   re   IterAll	itertoolsislice_TAB_COMPLETE_MAX_RESULTSstrr>   )r)   itcs      r"   runzCloudListingRequestThread.run   sd    	
!''A  "((-FGG1AGDL s   A))r   r   r   r1   r*   rs   __classcell__)rh   s   @r"   r`   r`      s    Hr!   r`   c                       e Zd Zy)TimeoutErrorN)r   r   r   r    r!   r"   rv   rv      s    r!   rv   c                   $    e Zd ZdZddZd Zd Zy)CloudObjectCompleterz Completer object for Cloud URLs.c                      || _         || _        y)zInstantiates completer for Cloud URLs.

    Args:
      gsutil_api: gsutil Cloud API instance to use.
      bucket_only: Whether the completer should only match buckets.
    N)re   _bucket_only)r)   rg   bucket_onlys      r"   r*   zCloudObjectCompleter.__init__   s     "D#Dr!   c                     t        || j                        }|j                          |j                  |       |j	                         r&ddl}|j                  t        |z         t               |j                  }|S )a<  Perform a remote listing request for the given wildcard URL.

    Args:
      wildcard_url: The wildcard URL to list.
      timeout: Time limit for the request.
    Returns:
      Cloud resources matching the given wildcard URL.
    Raises:
      TimeoutError: If the listing does not finish within the timeout.
    r   N)
r`   re   startjoinis_aliveargcompletewarn_TIMEOUT_WARNINGrv   r>   )r)   wildcard_urltimeoutrequest_threadr   r>   s         r"   _PerformCloudListingz)CloudObjectCompleter._PerformCloudListing   sm     /|T=M=MNN   ''12N$$GNr!   c                    |sd}nt        |      rg S |dz   }t        |      }| j                  r|j                         sg S t        j
                  j                  ddd      }|dk(  rg S t        j                         }t        j                  t                     }|j                  |      }d}	||}
d}	na	 | j                  ||      }
| j                  rt        |
      d	k(  rt        |
d         g}
t        |
      t        k(  }|j!                  ||
|       |j%                  t                      t        j                         }t        |
      }||z
  }t'        d||	|||z  |fz         |
S # t"        $ r d
}	g }
Y dw xY w)Nzgs://*GSUtiltab_completion_timeout   r    z (from cache)   z (request timeout)z:%s results%s in %.2fs, %.2f results/second for prefix: %s
)r   r	   rz   IsBucketbotoconfiggetintrO   r<   rL   r   rT   r   lenr
   ro   rV   rv   r]   _WriteTimingLog)r)   r-   r.   r   urlr   
start_timecachecached_resultstiming_log_entry_typer>   r@   end_timenum_resultselapsed_secondss                  r"   r/   zCloudObjectCompleter.__call__   s   f		 iC<L
|
,Cikk  +CQGG!|iJ++,I,KLE++F3N!g-++L'BW!2"71:./'w<+DD&'?;
 
356yy{Hg,K+OE	+_		&	0	01
 N   4s   5A E* *E:9E:N)F)r   r   r   r1   r*   r   r/   r    r!   r"   rx   rx      s    ($6-r!   rx   c                       e Zd ZdZd Zd Zy)CloudOrLocalObjectCompleterzCompleter object for Cloud URLs or local files.

  Invokes the Cloud object completer if the input looks like a Cloud URL and
  falls back to local file completer otherwise.
  c                 B    t        |      | _        t               | _        y r,   )rx   cloud_object_completerr$   r5   )r)   rg   s     r"   r*   z$CloudOrLocalObjectCompleter.__init__#  s    "6z"BD"6"8Dr!   c                 \    t        |      r| j                  }n| j                  } ||fi |S r,   )r   r5   r   )r)   r-   r.   	completers       r"   r/   z$CloudOrLocalObjectCompleter.__call__'  s0    v--i--iV&v&&r!   Nr0   r    r!   r"   r   r     s    9'r!   r   c                       e Zd ZdZd Zy)NoOpCompleterz(Completer that always returns 0 results.c                     g S r,   r    )r)   unused_prefixunused_kwargss      r"   r/   zNoOpCompleter.__call__2  s    Ir!   N)r   r   r   r1   r/   r    r!   r"   r   r   /  s
    0r!   r   c                    | t         j                  k(  rt        |      S | t         j                  k(  r
t	               S | t         j
                  k(  r
t               S | t         j                  k(  rt        |d      S | t         j                  k(  rt        |      S | t         j                  k(  r
t               S t        d| z        )a  Create a completer instance of the given type.

  Args:
    completer_type: The type of completer to create.
    gsutil_api: gsutil Cloud API instance to use.
  Returns:
    A completer instance.
  Raises:
    RuntimeError: if completer type is not supported.
  T)r{   zUnknown completer "%s")r   r   r   r   r$   r   r3   r   rx   r   r   r   RuntimeError)completer_typerg   s     r"   MakeCompleterr   6  s     }:::&z22333!!AAA*,,333
==333
++,,,?
/.@
AAr!   c                     t         j                  j                  ddd      r/t        t	               d      5 }|j                  |        ddd       yy# 1 sw Y   yxY w)zAWrite an entry to the tab completion timing log, if it's enabled.r   tab_completion_time_logsFabN)r   r   getboolrD   r   rZ   )messagerJ   s     r"   r   r   Q  sJ    	[[#=uE	)+T	2bhhw 
3	2 F	2	2s   AA)(r1   
__future__r   r   r   r   rm   rE   	threadingrO   r   boto.gs.aclr   gslib.storage_urlr   r	   r
   gslib.utils.boto_utilr   r   gslib.wildcard_iteratorr   rP   ro   rstripr   objectr   r$   r3   r<   Threadr`   rH   rv   rx   r   r   r   r   r    r!   r"   <module>r      s     & %  '      ( - 2 + ? = :    FH F 26 2'f 'O Od	 0 0 29 U6 Up'& '&F B6r!   