
    G                     >   S r SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSK	J
r
  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SS/r/ SQrS S jr S r!S r"S r#S r$S r%S!S jr&S r' " S S\(5      r)g)"zCUtility functions and class for listing commands such as ls and du.    )absolute_import)print_function)division)unicode_literalsN)EncryptionException)CommandException)PluralityCheckableIterator)GenerationFromUrlAndString)S3_ACL_MARKER_GUID)S3_DELETE_MARKER_GUID)S3_MARKER_GUIDS)UTF8)
IS_WINDOWS)AclTranslation)	text_util)StorageUrlFromStringmd5Hashcrc32c)aclcacheControlcomponentCountcontentDispositioncontentEncodingcontentLanguagecontentType
customTime
kmsKeyNamecustomerEncryptionetageventBasedHold
generationmetadatametagenerationretentionExpirationTimesizestorageClasstemporaryHoldtimeCreatedtimeDeletedtimeStorageClassUpdatedupdatedc                 \    SR                  SU-  S-  U -   S-   R                  S5      U5      $ )a  Returns a string with a vertically aligned label and value.

Labels of the same indentation level will start at the same column. Values
will all start at the same column (unless the combined left-indent and
label length is excessively long). If a value spans multiple lines,
indentation will only be applied to the first line. Example output from
several calls:

    Label1:            Value (default indent of 1 was used)
        Sublabel1:     Value (used indent of 2 here)
    Label2:            Value

Args:
  label: The label to print in the first column.
  value: The value to print in the second column.
  indent: (4 * indent) spaces will be placed before the label.
Returns:
  A string with a vertically aligned label and value.
z{}{}    :   )formatljust)labelvalueindents      (platform/gsutil/gslib/utils/ls_helper.pyMakeMetadataLiner7   F   s3    ( 
v)U2S8??CU	KK    c                     g)zDefault function for printing headers for buckets.

Header is printed prior to listing the contents of the bucket.

Args:
  bucket_listing_ref: BucketListingRef of type BUCKET.
N bucket_listing_refs    r6   PrintBucketHeaderr=   ]   s     r8   c                 D    [         R                  " U R                  5        g)z{Default function for printing buckets or prefixes.

Args:
  bucket_listing_ref: BucketListingRef of type BUCKET or PREFIX.
N)r   print_to_fd
url_stringr;   s    r6   PrintDirrA   h   s     *556r8   c                     g)zOff-by-default function for printing buckets or prefix size summaries.

Args:
  num_bytes: Number of bytes contained in the directory.
  bucket_listing_ref: BucketListingRef of type BUCKET or PREFIX.
Nr:   )	num_bytesr<   s     r6   PrintDirSummaryrD   r   s     r8   c                 b    [         R                  " SR                  U R                  5      5        g)zDefault function for printing headers for prefixes.

Header is printed prior to listing the contents of the prefix.

Args:
  bucket_listing_ref: BucketListingRef of type PREFIX.
{}:N)r   r?   r1   r@   r;   s    r6   PrintDirHeaderrG   |   s"     %7%B%BCDr8   c                  .    [         R                  " 5         g)z<Default function for printing new lines between directories.N)r   r?   r:   r8   r6   PrintNewLinerI      s    r8   c                    U R                   n[        U5      nU R                  nUR                  (       a(  [        UR                  R
                  ;   a
  SnSnUS-  nOUR                  nSn[        R                  " SR                  U5      5        UR                  (       a9  [        R                  " [        SUR                  R                  S5      5      5        UR                  (       a9  [        R                  " [        SUR                  R                  S5      5      5        UR                  (       aS  UR                  UR                  :w  a9  [        R                  " [        SUR                  R                  S5      5      5        UR                  (       a*  [        R                  " [        S	UR                  5      5        UR                   (       a   [        R                  " [        S
S5      5        UR"                  (       a   [        R                  " [        SS5      5        UR$                  (       a9  [        R                  " [        SUR$                  R                  S5      5      5        UR&                  (       a*  [        R                  " [        SUR&                  5      5        UR(                  (       a*  [        R                  " [        SUR(                  5      5        UR*                  (       a*  [        R                  " [        SUR*                  5      5        UR,                  (       a*  [        R                  " [        SUR,                  5      5        UR.                  (       a*  [        R                  " [        SUR.                  5      5        [        R                  " [        SUR                  5      5        [        R                  " [        SUR0                  5      5        UR2                  (       a*  [        R                  " [        SUR2                  5      5        UR4                  (       a*  [        R                  " [        SUR4                  5      5        UR6                  (       a9  [        R                  " [        SUR6                  R                  S5      5      5        0 nUR                  (       a  UR                  R
                  (       a  / nUR                  R
                   HB  n	U	R8                  [:        ;  a  UR=                  U	5        M*  U	R>                  XyR8                  '   MD     U(       a  [        R                  " [        SS5      5        U HY  n
SR                  U
R8                  5      nSR                  U
R>                  5      n[        XSS9n[        R                  " U5        M[     UR@                  (       a  URB                  (       d   [        R                  " [        SS5      5        URD                  (       d   [        R                  " [        SS5      5        [        R                  " [        S UR@                  RF                  5      5        [        R                  " [        S!UR@                  RH                  5      5        URB                  (       a*  [        R                  " [        SURB                  5      5        URD                  (       a*  [        R                  " [        SURD                  5      5        [        R                  " [        S"URJ                  RM                  S#5      5      5        URN                  (       a5  [Q        X4RN                  5      n[        R                  " [        S$U5      5        URR                  (       a*  [        R                  " [        S%URR                  5      5        U(       a  URT                  (       aA  [        R                  " [        S&[V        RX                  " URT                  5      5      5        Xe4$ [Z        U;   a*  [        R                  " [        S&U[Z           5      5        Xe4$ [        R                  " [        S&S'5      5        Xe4$ )(a  Print full info for given object (like what displays for gsutil ls -L).

Args:
  bucket_listing_ref: BucketListingRef being listed.
                      Must have ref_type OBJECT and a populated root_object
                      with the desired fields.
  incl_acl: True if ACL info should be output.

Returns:
  Tuple (number of objects, object_length)

Raises:
  Exception: if calling bug encountered.
r   z<DeleteMarker>   rF   zCreation timez%a, %d %b %Y %H:%M:%S GMTzUpdate timezStorage class update timezStorage classzTemporary HoldEnabledzEvent-Based HoldzRetention ExpirationzKMS keyzCache-ControlzContent-DispositionzContent-EncodingzContent-LanguagezContent-LengthzContent-TypezComponent-CountzCustom-TimezNoncurrent timeMetadata z{}   )r5   zHash (crc32c)	encryptedz
Hash (md5)zEncryption algorithmzEncryption key SHA256ETagz"'
GenerationMetagenerationACLz[]).r@   r   root_objectr"   r   additionalPropertiesr%   r   r?   r1   r(   r7   strftimer+   r*   r&   r'   r    r$   r   r   r   r   r   r   r   r   r)   keyr   appendr4   r   r   r   encryptionAlgorithm	keySha256r   stripr!   r
   r#   r   r   JsonFromMessager   )r<   incl_aclurl_strstorage_urlobjrC   num_objsmarker_propsnon_marker_propsadd_propapap_keyap_valuemeta_data_linegeneration_strs                  r6   PrintFullInfoAboutObjectrk      s    ))'$W-+&&#	lls||@@@IHGIHW-.__112MN	PQ 	[[--.IJ	LM 
!!	!!S__4'''001LM	OP 	*?C<L<LMN*+;YGH*+=yIJ  "''001LM	OP 	^^*9cnnEF*?C<L<LMN.0F0FGI+S-@-@AC+S-@-@AC()9388DE(IJ*C,>,>?A^^*=#..IJ__*112MN	PQ ,\\cll77LL55	_	,)%-^^\\"	 6
 ,Z<= "RVV$;;rxx()&1En-	 !
 	::,_kJK;;,\;GH///CC	EF 0//99	;< 	ZZ*?CJJGH[[*<EF(1FGH^^/^^LN*<HI*+;+.+=+=? @ ww
5."@"@"I
JL 	 
|	+
5,/A"B
CE 	 ,UD9:
	r8   c                      [         R                  " U R                  5        g! [         a&  n[        (       a  UR
                  S:X  d  e  SnAgSnAff = f)zDefault printing function for objects.

Args:
  bucket_listing_ref: BucketListingRef of type OBJECT.

Returns:
  (num_objects, num_bytes).
r   N)rK   r   )r   r?   r@   IOErrorr   errno)r<   es     r6   PrintObjectrp     sO    ,778 
 
  J177a< (	s    # 
AAAc                   N    \ rS rSrSr\\\\\	\
SSSSS4S jrS rSS	 jrS
 rSrg)LsHelperi$  zHelper class for ls and du.FN)nameTc                     Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        Xl
        Xl        Xl        g)a+  Initializes the helper class to prepare for listing.

Args:
  iterator_func: Function for instantiating iterator.
                 Inputs-
                   url_string- Url string to iterate on. May include
                               wildcards.
                   all_versions=False- If true, iterate over all object
                                       versions.
  logger: Logger for outputting warnings / errors.
  print_object_func: Function for printing objects.
  print_dir_func:    Function for printing buckets/prefixes.
  print_dir_header_func: Function for printing header line for buckets
                         or prefixes.
  print_bucket_header_func: Function for printing header line for buckets
                            or prefixes.
  print_dir_summary_func: Function for printing size summaries about
                          buckets/prefixes.
  print_newline_func: Function for printing new lines between dirs.
  all_versions:      If true, list all object versions.
  should_recurse:    If true, recursively listing buckets/prefixes.
  exclude_patterns:  Patterns to exclude when listing.
  fields:            Fields to request from bucket listings; this should
                     include all fields that need to be populated in
                     objects so they can be listed. Can be set to None
                     to retrieve all object fields. Defaults to short
                     listing fields.
  list_subdir_contents: If true, return the directory and any contents,
                        otherwise return only the directory itself.
N)_iterator_funclogger_print_object_func_print_dir_func_print_dir_header_func_print_bucket_header_func_print_dir_summary_func_print_newline_funcall_versionsshould_recurseexclude_patternsbucket_listing_fieldslist_subdir_contents)selfiterator_funcrv   print_object_funcprint_dir_funcprint_dir_header_funcprint_bucket_header_funcprint_dir_summary_funcprint_newline_funcr}   r~   r   fieldsr   s                 r6   __init__LsHelper.__init__'  sR    X (K/)"7%="#9 1$(,!' 4r8   c           	      0   SnSnSnSnUR                  5       (       d  U R                  (       a@  UR                  5       (       a  U R                  U5        U R                  UR                  SS9$ UR                  5       (       a  UR                  nOUR                  5       n[        U R                  X`R                  S9R                  SU R                  S95      nUR                  5       n UR                  5         U GH.  n	U R!                  U	5      (       a  M  U	R#                  5       (       a  Sn
U R%                  U	5      u  pSnOU	R'                  5       (       a  U(       a  U R)                  5         OSnU(       a#  U R*                  (       a  U R-                  U	5        OU(       a  U R*                  (       d  Sn[/        U	R                  5      R                  U R*                  (       a  S	OSS9nU R                  U5      u  pnU R1                  X5        O[3        S
5      eX+-  nX:-  nXL-  nGM1     X2U4$ ! [         aV    [        U R                  UR                  SS9U R                  S9R                  S[        S95      nUR                  5       n GNf = f)zIterates over the given URL and calls print functions.

Args:
  url: StorageUrl to iterate over.

Returns:
  (num_objects, num_bytes) total number of objects and bytes iterated.
r   F)print_initial_newliner}   Texpand_top_level_bucketsr   Nwildcard_suffix*z?Sub-level iterator returned a CsBucketListingRef of type Bucket)IsBucketr~   rz   _RecurseExpandUrlAndPrintr@   HasGenerationCreatePrefixUrlr	   ru   r}   IterAllr   HasPluralityPeekExceptionr   UNENCRYPTED_FULL_LISTING_FIELDS_MatchesExcludedPatternIsObjectrw   IsPrefixr|   r   ry   r   r{   r   )r   urlnum_objectsnum_dirsrC   print_newlineiteration_urltop_level_iterator	pluralityblrndnonbexpansion_url_strs                 r6   ExpandUrlAndPrintLsHelper.ExpandUrlAndPrinta  s    KHIM
||~~,,	&&s+++CNNBG , I I
 
				++-5


*;*;  ==DW+/(,(B(B >E >DE
 %113i6((* $#'',,
<<>>"**3/&"-\\^^$$& M444'',!:!:!M2nn-o)-)B)B# . N  556GH*""

&
&r
/ !OQ Q	7 $8 I--Q ! 
6 8##D#9!..   007-1*I 18 1KL '335	
6s   ,H5 5AJJc                    SnSnSnU R                  SU-  U R                  S9R                  SU R                  S9 GH  nU R	                  U5      (       a  M  UR                  5       (       a  SnU R                  U5      u  pOUR                  5       (       a  U R                  (       as  U(       a  U R                  5         OSnU R                  U5        [        UR                  5      R                  SS9n
U R                  U
5      u  pxn	U R                  X5        O"Su  pxn	U R!                  U5        O[#        S	5      eXG-  nX8-  nXY-  nGM     XCU4$ )
ak  Iterates over the given URL string and calls print functions.

Args:
  url_str: String describing StorageUrl to iterate over.
           Must be of depth one or higher.
  print_initial_newline: If true, print a newline before recursively
                         expanded prefixes.

Returns:
  (num_objects, num_bytes) total number of objects and bytes iterated.
r   z%sr   Tr   r   r   )rK   r   r   z=Sub-level iterator returned a bucketListingRef of type Bucket)ru   r}   r   r   r   r   rw   r   r~   r|   ry   r   r@   r   r   r{   rx   r   )r   r_   r   r   r   rC   r   r   r   r   r   s              r6   r   "LsHelper._RecurseExpandUrlAndPrint  sb    KHI""wT%6%6 # 88?%)"&"<"< 9@ 9>> 
	%	%c	*	*	((-B<<>>"$$&$(!

%
%c
*2nn-ocoB  556GH*""

&
&r
/*""


s
# KM 	Mnhkoi?>B )++r8   c                     U R                   (       ae  [        R                  " UR                  5      nU R                    H5  n[        R                  " U[        R                  " U5      5      (       d  M5    g   g)zChecks bucket listing reference against patterns to exclude.

Args:
  blr: BucketListingRef to check.

Returns:
  True if reference matches a pattern and should be excluded.
TF)r   six
ensure_strr@   fnmatch)r   r   tomatchpatterns       r6   r    LsHelper._MatchesExcludedPattern  sQ     s~~.g**'??7CNN7$;<< + r8   )ru   rz   rx   ry   r{   r|   rw   r}   r   r   r   rv   r~   T)__name__
__module____qualname____firstlineno____doc__rp   rA   rG   r=   rD   rI   r   r   r   r   __static_attributes__r:   r8   r6   rr   rr   $  s@    #
 "-&%3(9&5".!# $$(85tL.\0,dr8   rr   )rK   r   )*r   
__future__r   r   r   r   r   sysr   gslib.cloud_apir   gslib.exceptionr   "gslib.plurality_checkable_iteratorr	   gslib.storage_urlr
   gslib.utils.constantsr   r   r   r   gslib.utils.system_utilr   gslib.utils.translation_helperr   gslib.utilsr   gslib.wildcard_iteratorr   ENCRYPTED_FIELDSr   r7   r=   rA   rD   rG   rI   rk   rp   objectrr   r:   r8   r6   <module>r      s    J & %  '  
 
 / , I 8 4 7 1 & . 9 ! 8  # 6L.7EAH&Kv Kr8   