
    y                        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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dlmZ ddlmZ ddlmZ ddlmZ ddlZdZ ej@                  d      Z! ej@                  d      Z" e#dde	jH                  z   dde	jH                  z   g      Z%d Z&d Z'dddejP                  jR                  dddddejT                  jV                  ejX                  jV                  dejZ                  j\                  ddddfdZ/d Z0 G d d ejb                  ejd                              Z3 G d de3      Z4 G d d e3      Z5 G d! d"      Z6d# Z7y)$z1Utilities for expanding wildcarded GCS pathnames.    )absolute_import)division)unicode_literalsN)Iterator)api_factory)	cloud_api)errors)request_config_factory)folder_util)storage_url)resource_reference)log)debug_outputz!Expected files but got stream: {}z\*{3,}z[*?\[\]].z..c                 d    | j                  t        j                        d   j                  d      S )N   r   )
rpartitionossep
startswith)paths    ;lib/googlecloudsdk/command_lib/storage/wildcard_iterator.py
_is_hiddenr   3   s%    		 	#	.	.s	33    c                 >    t        t        j                  |             S )zChecks whether url_string contains a wildcard.

  Args:
    url_string: URL string to check.

  Returns:
    bool indicator.
  )boolWILDCARD_REGEXsearch)
url_strings    r   contains_wildcardr    7   s     
n##J/	00r   TFc                    t        j                  |       }t        |t         j                        rt	        |||||||||
||||||      S t        |t         j
                        rt        |||||	|      S t        j                  d|z        )a  Instantiate a WildcardIterator for the given URL string.

  Args:
    url_str (str): URL string which may contain wildcard characters.
    error_on_missing_key (bool): If true, and the encryption key needed to
      decrypt an object is missing, the iterator raises an error for that
      object.
    exclude_patterns (Patterns|None): Don't return resources whose URLs or local
      file paths matched these regex patterns.
    fetch_encrypted_object_hashes (bool): Fall back to GET requests for
      encrypted cloud objects in order to fetch their hash values.
    fields_scope (cloud_api.FieldsScope): Determines amount of metadata returned
      by API.
    files_only (bool): Skips containers. Raises error for stream types. Still
      returns symlinks.
    force_include_hidden_files (bool): Include local hidden files even if not
      recursive iteration. URL should be for directory or directory followed by
      wildcards.
    get_bucket_metadata (bool): If true, perform a bucket GET request when
      fetching bucket resources.
    halt_on_empty_response (bool): Stops querying after empty list response. See
      CloudApi for details.
    ignore_symlinks (bool): Skip over symlinks instead of following them.
    managed_folder_setting (folder_util.ManagedFolderSetting): Indicates how to
      deal with managed folders.
     folder_setting (folder_util.FolderSetting): Indicates how to deal with
       folders.
    next_page_token (str|None): Used to resume LIST calls.
    object_state (cloud_api.ObjectState): Versions of objects to query.
    preserve_symlinks (bool): Preserve symlinks instead of following them.
    raise_managed_folder_precondition_errors (bool): If True, raises
      precondition errors from managed folder listing. Otherwise, suppresses
      these errors. This is helpful in commands that list managed folders by
      default.
    soft_deleted_buckets (bool): If true, soft deleted buckets will be queried.
    list_filter (str|None): If provided, objects with matching filters
      will be returned, The prefixes would still be returned regardless of
      whether they match the specified filter, See
      go/gcs-object-context-filtering for more details.

  Returns:
    A WildcardIterator object.
  )error_on_missing_keyexclude_patternsfetch_encrypted_object_hashesfields_scope
files_onlyget_bucket_metadatahalt_on_empty_responsemanaged_folder_settingfolder_settingnext_page_tokenobject_state(raise_managed_folder_precondition_errorssoft_deleted_bucketslist_filter)r#   r&   force_include_hidden_filesignore_symlinkspreserve_symlinkszUnknown url type %s.)	r   storage_url_from_string
isinstanceCloudUrlCloudWildcardIteratorFileUrlFileWildcardIteratorcommand_errorsInvalidUrlError)url_strr"   r#   r$   r%   r&   r0   r'   r(   r1   r)   r*   r+   r,   r2   r-   r.   r/   urls                      r   get_wildcard_iteratorr=   C   s    ~ 	++G4#[))* 1)&C!/55%'!1Y1 " #{**+)#='+  
(
()?#)E
FFr   c                     t        j                  t        d| j                        }| j                  |d| j                  z   z  }t        j                  |      S )zAsterisk counts greater than two treated as single * to mimic globs.

  Args:
    url (StorageUrl): Url to compress wildcards in.

  Returns:
    StorageUrl built from string with compressed wildcards.
  *#)resubCOMPRESS_WILDCARDS_REGEXversionless_url_string
generationr   r3   )r<   compressed_url_strings     r   _compress_url_wildcardsrG      sQ     &&!93!$!;!;=^^S3>>11		,	,-B	CCr   c                   "    e Zd ZdZ	 	 ddZd Zy)WildcardIteratora  Class for iterating over Google Cloud Storage strings containing wildcards.

  The base class is abstract; you should instantiate using the
  wildcard_iterator() static factory method, which chooses the right
  implementation depending on the base string.
  Nc                 @    t        |      | _        || _        || _        y)z@Initializes class. See get_wildcard_iterator for Args docstring.N)rG   _url_exclude_patterns_files_only)selfr<   r#   r&   s       r   __init__zWildcardIterator.__init__   s      (,DI-D!Dr   c                 6    dt        | j                  dd      z  S )z2Returns string representation of WildcardIterator.zWildcardIterator(%s)r   N)getattrrK   rN   s    r   __repr__zWildcardIterator.__repr__   s    !GDII|T$JJJr   )NF)__name__
__module____qualname____doc__rO   rS    r   r   rI   rI      s     		"Kr   rI   c                   4     e Zd ZdZ	 	 	 	 	 d fd	Zd Z xZS )r8   z,Class to iterate over files and directories.c                    t         t        |   |||       || _        || _        |rD|j
                  j                  d      d   t        j                  k7  rt        j                  d      | j                  j
                  | _        d| j                  v | _        | j                  xs |xs t        | j                        | _        y)ae  Initialize FileWildcardIterator instance.

    Args:
      url (FileUrl): A FileUrl instance representing a file path.
      exclude_patterns (Patterns|None): See get_wildcard_iterator.
      files_only (bool): Returns files and symlinks, skips folders, errors on
        streams.
      force_include_hidden_files (bool): Include hidden files even if not
        recursive iteration. URL should be for directory or directory followed
        by wildcards.
      ignore_symlinks (bool): Skip over symlinks instead of following them.
      preserve_symlinks (bool): Preserve symlinks instead of following them.
    )r&   r?   z`If force-including hidden files, input URL must be directory or directory followed by wildcards.**N)superr8   rO   _ignore_symlinks_preserve_symlinksresource_namerstripr   r   r9   r:   rK   _path_recurser   _include_hidden_files)rN   r<   r#   r&   r0   r1   r2   	__class__s          r   rO   zFileWildcardIterator.__init__   s    , 

. / 
 ,D/D 	#$$S)"-7**.  ((DJDJJ&DMM3Mz$**7M 	r   c              #     
K   | j                   j                  rj| j                  r<t        j                  t
        j                  | j                   j                              t        j                  | j                          y | j                  t        v r"t        j                  | j                          y t        j                  | j                        j                         }|j                   rAt#        |j$                  dd        }t'        j(                  j*                  | }|j,                  }nd}| j                  }|j/                  d      r t&        j(                  j+                  |d      }dt&        j0                  z   }| j                  j3                  |      r|
nd

fdt        j                  |      j5                  |      D        }|D ]5  }| j6                  r| j6                  j9                  |      s| j:                  st=        |      rC| j                  rqt&        j(                  j?                  |      sRtA        jB                  |      r<t        j                  t
        j                  | j                   j                              t&        j(                  jE                  |      }|r]| jF                  sQt&        j(                  jI                  |      s| jJ                  r&tM        jN                  dj                  |             >| j                  j/                  d      rN|r| jF                  s@t&        j(                  jQ                  |      rt&        j(                  jI                  |      rtA        jR                  |      }	|s8t&        j(                  jI                  |      rt        j                  |	       |r%| jF                  rt        jT                  |	       t        j                  |	|       8 y w)	N   r   r\   r?    c              3   :   K   | ]  }t        |      z     y wN)str).0ppath_prefixs     r   	<genexpr>z0FileWildcardIterator.__iter__.<locals>.<genexpr>  s"      ?A 	c!f?s   zSkipping symlink {})
is_symlink)+rK   is_stdiorM   r9   r:   _FILES_ONLY_ERROR_FORMATformatr`   r   FileObjectResourcerb   _RELATIVE_PATH_SYMBOLSFileDirectoryResourcepathlibPath
expanduserrootlistpartsr   r   joinanchorendswithr   r   globrL   matchrd   r   isfiler   is_named_pipeislinkr_   isdirr^   r   warningexistsr7   FileSymlinkPlaceholderResource)rN   pathlib_path path_components_relative_to_rootpath_relative_to_rootrz    current_working_directory_prefixpath_iteratorr   rp   file_urlrn   s             @r   __iter__zFileWildcardIterator.__iter__   s    yy			,,$++DII,C,CD
 	
 11$))<<zz++ 44TYY??<<

+668L *.l.@.@.D)E& ggll,LM  dd"jj%%d+ ggll+@#F (+RVV|$zz=>4kkd#(()>?M
 

 
 T%;%;%A%A$%G((Z-=			"''.."6$$T*..&--dii.E.EF  	
 77>>$'j
))ww}}T"d&;&;)0067 **

d
#$"9"977>>$'277==+>$$T*hBGGMM$/ 66x@@$11 ??II 33
 	
U s   P
P)NFFFF)rT   rU   rV   rW   rO   r   __classcell__re   s   @r   r8   r8      s#    4
 !&*XV
r   r8   c                       e Zd ZdZdddej
                  j                  dddej                  j                  ej                  j                  dej                  j                  dddf fd	Zd Zd Zd Zdd	Zd
 Z	 ddZ	 ddZd ZddZddZd Zd Zd Zdedeej<                     fdZdedeej<                     fdZ d Z! xZ"S )r6   zAClass to iterate over Cloud Storage strings containing wildcards.TNFc                    t         t        |   |||       t        j                  | j
                  j                        | _        || _        || _	        || _
        || _        || _        |	| _        |
| _        || _        || _        || _        || _        || _        |t(        j*                  j,                  u r6| j
                  j.                   t(        j*                  j0                  | _        n|| _        |t(        j*                  j4                  u | _        | j                   t(        j*                  j0                  u xs& | j6                  xr | j
                  j.                  du | _        y)a  Instantiates an iterator that matches the wildcard URL.

    Args:
      url (CloudUrl): CloudUrl that may contain wildcard that needs expansion.
      error_on_missing_key (bool): If true, and the encryption key needed to
        decrypt an object is missing, the iterator raises an error for that
        object.
      exclude_patterns (Patterns|None): See get_wildcard_iterator.
      fetch_encrypted_object_hashes (bool): Fall back to GET requests for
        encrypted objects in order to fetch their hash values.
      fields_scope (cloud_api.FieldsScope): Determines amount of metadata
        returned by API.
      files_only (bool): Returns cloud objects, not prefixes or buckets. Also
        skips directory placeholder objects, although they are technically
        objects.
      get_bucket_metadata (bool): If true, perform a bucket GET request when
        fetching bucket resources. Otherwise, bucket URLs without wildcards may
        be returned without verifying the buckets exist.
      halt_on_empty_response (bool): Stops querying after empty list response.
        See CloudApi for details.
      managed_folder_setting (folder_util.ManagedFolderSetting): Indicates how
        to deal with managed folders.
      folder_setting (folder_util.FolderSetting): Indicates how to deal with
        folders.
      next_page_token (str|None): Used to resume LIST calls.
      object_state (cloud_api.ObjectState): Versions of objects to query.
      raise_managed_folder_precondition_errors (bool): If True, raises
        precondition errors from managed folder listing. Otherwise, suppresses
        these errors. This is helpful in commands that list managed folders by
        default.
      soft_deleted_buckets (bool): If true, soft deleted buckets will be
        queried.
      list_filter (str|None): If provided, objects with matching
        contexts will be returned. The prefixes would still be returned
        regardless of whether they match the specified context, See
        go/gcs-object-context-filtering for more details.
    )r#   r&   N)r]   r6   rO   r   get_apirK   scheme_client_error_on_missing_key_fetch_encrypted_object_hashes_fields_scope_get_bucket_metadata_halt_on_empty_response_managed_folder_setting_folder_setting_next_page_token_object_state)_raise_managed_folder_precondition_errors_soft_deleted_buckets_list_filterr   ObjectStateLIVErE   LIVE_AND_NONCURRENT_object_state_for_listingSOFT_DELETED_soft_deleted _object_state_requires_expansion)rN   r<   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   re   s                   r   rO   zCloudWildcardIterator.__init__U  sF   n 

/.: 0  &&tyy'7'78DL!5D*GD'%D 3D#9D #9D )D+D%D0 	2 "6D#D 		--222II  ,'0'<'<'P'Pd$'3d$%)>)>)K)KKDi33GGG 	A?499#7#74#? 	)r   c              #     K   | j                   r5| j                  j                         s| j                  j                         ry | j                  j                         r;| j                  j                  | j                  | j                        D ]  }|  y | j                         D ]  }| j                  j                         r| #| j                  |j                  j                        }| j                  |j                  j                  |      D ]/  }| j                  r0| j                  j                  |j                  j                        r@| j                   r]t!        |t"        j$                        rB|j                  j&                  j)                  t        j*                        r|j,                  dk(  r| j.                  t0        j2                  j4                  u rt!        |t"        j6                        s| j8                  t0        j:                  j4                  u rt!        |t"        j<                        s,| 2  y w)Nr%   soft_deleted)is_hns_bucketr   )rM   rK   is_provider	is_bucketr   list_bucketsr   r   _fetch_buckets_is_hns_bucketr   bucket_name_fetch_sub_bucket_resourcesrL   r   rD   r4   r   ObjectResourcer`   r   CLOUD_URL_DELIMITERsizer   r   ManagedFolderSettingLIST_WITHOUT_OBJECTSManagedFolderResourcer   FolderSettingFolderResource)rN   bucket_resourcebucket_or_unknown_resourcer   resources        r   r   zCloudWildcardIterator.__iter__  s    TYY224		8K8K8Myy!\\66))11 7 / 	 )-(;(;(=
$99 *
* --(44@@- ::(44@@) ; h %%$*@*@*F*F$$;;+ x);)J)JK((66??#77 !*  ,,33HHI"0FF  $$,,AAB"8-?-N-NONI )>s   IIc                 x   | j                   rt        j                  j                  | j                  j
                  v r{| j                  t        j                  j                  k7  rSt        |t        j                        r8|j                  s+|j                  s|j                  r\| j                  j                  |j                   |j"                  | j$                  j&                  | j                  | j(                        S |j*                  rt-        j.                  |j0                  |j*                  | j2                        }t5        |j6                  dd       r]| j                  j                  |j                   |j"                  || j$                  j&                  | j                  | j(                        S |S )NrE   r%   r   )decryption_key_hash_sha256r"   decryption_key)r   r   
Capability
ENCRYPTIONr   capabilitiesr   FieldsScopeSHORTr4   r   r   crc32c_hashmd5_hashkms_keyget_object_metadatabucketnamerK   rE   r   r   r
   get_request_configr   r   rQ   resource_args)rN   r   request_configs      r   _decrypt_resource_if_necessaryz4CloudWildcardIterator._decrypt_resource_if_necessary  sW   ++  ++t||/H/HH)"7"7"="==x!3!B!BC%%):): 
		||//OOMMyy++++++ 0 
 	
 
	,	,/BB  '/'J'J!%!;!;= >//1A4H11oomm------ 2   Or   c                 r   	 | j                   j                  || j                  j                  t	        j
                  | j                        | j                  j                  | j                  | j                        }| j                  |      S # t        j                  $ r Y yt        j                  $ r}|j                  dk(  rhdt        |      v r[| j                  j                  j!                  | j                  j"                        r"| j                  rt%        j&                  d       n Y d}~yd}~ww xY w)z/Matches user input that doesn't need expansion.r   i  zYou must specify a generationzGET failed with "must specify generation" error. This is expected for a soft-deleted object listed with a trailing slash. Falling back to a LIST call.N)r   r   rK   r`   r
   r   rE   r   r   r   
api_errorsNotFoundErrorGcsApiErrorstatus_coderk   r   r   	delimiterr   debug)rN   r   r   es       r   _try_getting_object_directlyz2CloudWildcardIterator._try_getting_object_directly  s
   11

))
!
!
 
3
3DII
>YY)))))) 2 h 00::## 
" ! !!  --3
-Q7ii""++DII,?,?@  		3	

 	 	 !s   B
B D6"D64A8D11D6c                 &   t        | j                  j                        xsG | j                  xs9 | j                  j                  j                  | j                  j                        }|s| j                  |      }|r|gS | j                  ||      S )z:Fetch all objects for the given bucket that match the URL.)	r    rK   r`   r   r   r   r   r   _expand_object_path)rN   r   r   needs_further_expansiondirect_query_results        r   r   z1CloudWildcardIterator._fetch_sub_bucket_resources/  s     	$))112 	>00	>99(()<)<= 
 # ==kJ	#$$##K??r   c              #     K   |j                   d u }| j                  t        j                  j                  t        j                  j
                  fv }	 |r^t        j                  j                  | j                  j                  v r.|r,| j                  j                  ||j                  xs d       }ng }|D ]  }|  y # t        j                  $ r | j                  r Y y w xY ww)Nr   prefix)r   r   r   r   LIST_WITH_OBJECTSr   r   r   MANAGED_FOLDERSr   r   list_managed_foldersr   r   PreconditionFailedErrorr   )rN   r   wildcard_partsis_recursive_expansionshould_list_managed_foldersmanaged_folder_iteratorr   s          r   _get_managed_folder_iteratorz2CloudWildcardIterator._get_managed_folder_iterator>  s      ,55="&">">((::((==C #
%""22dll6O6OO$"&,,"C"C#N,A,A,IT #D #
 #%-( .-- 		7	7 
8s+   AC&A-C  ?C&  C# C&"C##C&c              #     K   |j                   d u }| j                  t        j                  j                  u xr |}| j                  t        j                  j
                  fv xs |}|j                  r7|j                  j                  d      s|j                  dz   n|j                  }nd }|rPt        j                  j                  | j                  j                  v r |r| j                  j                  ||      }ng }|D ]  }	|	  y w)N/r   )r   r   r   r   LIST_AS_FOLDERSr   r   r   r   r   FOLDERSr   r   list_folders)
rN   r   r   r   r   is_list_as_foldersshould_list_foldersmodified_prefixfolder_iteratorr   s
             r   _get_folder_iteratorz*CloudWildcardIterator._get_folder_iteratorY  s     ,55= 9 9 I II 	 
 	%%::<	= 	    &&//4 

#
%$$  o 	  ((DLL,E,EE"11!  2 o
 o#n $s   D	Dc                    | j                   t        j                  j                  ur&| j                  t        j
                  j                  us|j                  r| j                   t        j                  j                  u xr& | j                  t        j
                  j                  u }t        |j                        }|s|sd nd}| j                  j                  ||j                  | j                  | j                  || j                  |j                  xs d | j                  | j                   	      }ng }| j#                  ||      }| j%                  |||      }	t'        j(                  |||	d       S )NT)	r   r   r%   r(   include_folders_as_prefixesr+   r   r,   r/   c                 .    | j                   j                  S rj   )r   r   )r   s    r   <lambda>z>CloudWildcardIterator._get_resource_iterator.<locals>.<lambda>  s    X11<<r   )key)r   r   r   r   r   r   r   DO_NOT_LISTr   r   list_objectsr   r   r   r   r   r   r   r   heapqmerge)
rN   r   r   r   setting_is_do_not_listuses_delimiterr   object_iteratorr   r   s
             r   _get_resource_iteratorz,CloudWildcardIterator._get_resource_iterator  sk   
 ((33HHI$$,,AAB ##
 
&
&--99: L""k&?&?&K&KK  N445n )$D " 11!",,))!%!=!=&A//&&.$55'' 2 
o o"??^ //^]O ;;<	 r   c                    t        |      t        j                  usp| j                  t        j
                  j                  t        j
                  j                  hvs0t        j                  j                  | j                  j                  vr|S 	 |j                  }| j                  j                  |j                  |j                         S # t"        j$                  $ r |cY S w xY w)zDIf resource is a prefix, attempts to convert it to a managed folder.)typer   PrefixResourcer   r   r   r   r   r   r   r   r   r   r   get_managed_folderr   r`   r   r   )rN   r   
prefix_urls      r   '_maybe_convert_prefix_to_managed_folderz=CloudWildcardIterator._maybe_convert_prefix_to_managed_folder  s    
 	X0???'',,>>,,AA


 //t||7P7PPo''j\\,,

 
 *":":  ## os   ;C C#"C#c                     t        |      t        j                  usp| j                  t        j
                  j                  t        j
                  j                  hvs0t        j                  j                  | j                  j                  vr|S | j                  t        j
                  j                  u r|s|S 	 |j                  }| j                  j                  |j                  |j                         S # t"        j$                  $ r |cY S w xY w)z<If resource is a prefix, attempts to convert it to a folder.)r  r   r  r   r   r   r   r   r   r   r   r   r   r   
get_folderr   r`   r   r   )rN   r   r   r  s       r   _maybe_convert_prefix_to_folderz5CloudWildcardIterator._maybe_convert_prefix_to_folder  s    
 	X0???%%::%%55


 ''t||/H/HHo 	 9 9 I IIo''j\\$$

 
 *":":  ## os   9;C5 5DDc              #     K   | j                   j                  }|j                  | j                   j                        rLt	        | j                   j                        s| j                  |      }|r| t        j                  |      }n|}t        j                  |g      }d}|r|j                         }t        j                  || j                   j                        }	| j                  ||	|      }
| j                  |
|	j                  |	j                   z         }|D ]5  }|j                  j                  }|	j"                  rut%        |      t&        j(                  u sBt*        j-                  |      r%t/        j0                  dj3                  |            }||j5                  ||	j"                  z          |j                  | j                   j                        s&|j                  | j                   j                        r| j7                  ||      }t9        |t&        j:                        s| j=                  |      }| j?                  |       8 |r|r|yw)a   Expands object names.

    Args:
      bucket_name (str): Name of the bucket.
      is_hns_bucket (bool): Whether the bucket is an HNS bucket.

    Yields:
      resource_reference.Resource objects where each resource can be
      an ObjectResource object or a PrefixResource object.
    NzECloud folders named with wildcards are not supported. API returned {}) rK   r`   r   r   r    r   r   rstrip_one_delimitercollectionsdequepopleftCloudWildcardPartsfrom_stringr  _filter_resourcesr   filter_patternsuffixr  r   r  r   r   r9   r:   rs   appendr  r4   r   r  r   )rN   r   r   original_object_namer   object_namenames_needing_expansionerrorr   r   resource_iteratorfiltered_resourcesr   resource_paths                 r   r   z)CloudWildcardIterator._expand_object_path  s      9922$$TYY%8%89tyy667"??L#
#445IJk(k)//>E
!$,,.d *55dDII<O<OPn 55
~}  11



."?"?
?
 )( ,,::   (^1@@@
 $$]3$44%%+VH%5e
 &,,."7"77 ''ii!!$--dii.A.AB
 99( H&8&G&GHCCHMH33H=
=K )+ "x k s   EI!!C9I!I!c                    |g}|j                  t        j                        s"|j                  |t        j                  z          d|v r$|j	                  dd      }|j                  |       n|}||fD ](  }|j                  d      s|j                  |dd        * |D cg c]*  }t        j                  t        j                  |            , c}S c c}w )a  Returns list of regex patterns derived from the wildcard patterns.

    Args:
      wildcard_pattern (str): A wilcard_pattern to filter the resources.

    Returns:
      List of compiled regex patterns.

    This translates the wildcard_pattern and also creates some additional
    patterns so that we can treat ** in a/b/c/**/d.txt as zero or more folders.
    This means, a/b/c/d.txt will also be returned along with a/b/c/e/f/d.txt.
    z/**/r   z**/   N)
r   r   r   r  replacer   rA   compilefnmatch	translate)rN   wildcard_patternwildcard_patternsupdated_patternpatternrm   s         r   _get_regex_patternsz)CloudWildcardIterator._get_regex_patternsN  s     **$$[%D%DE/*>> ? @ !! )00=o/(o$o6			E	" 	  - 7 7HH6GBJJw((+,6GHHHs   "/Cc              #   (  K   | j                  |      }|D ]x  }| j                  j                  r.|j                  j                  | j                  j                  k7  rG|D ]-  }|j	                  |j                  j
                        s)|  x z yw)aJ  Filter out resources that do not match the wildcard_pattern.

    Args:
      resource_iterator (iterable): An iterable resource_reference.Resource
        objects.
      wildcard_pattern (str): The wildcard_pattern to filter the resources.

    Yields:
      resource_reference.Resource objects matching the wildcard_pattern
    N)r(  rK   rE   r   r   r`   )rN   r  r$  regex_patternsr   regex_patterns         r   r  z'CloudWildcardIterator._filter_resourcest  s}      --.>?N%
))





)
)TYY-A-A
A)-x33AAB.
 * &s   BB
Bc                    t        | j                  j                        r%| j                  | j                  j                        S | j                  j	                         ry| j
                  rm| j                  r%| j                  | j                  j                        S | j                  j                  | j                  j                  | j                        gS t        j                  | j                        gS )zFetch the bucket(s) corresponding to the url.

    Returns:
      An iterable of BucketResource or UnknownResource objects.
    )r   r%   )r    rK   r   _list_buckets_matching_wildcardr   r   r   -_fetch_all_soft_deleted_generations_of_bucketr   
get_bucketr   r   UnknownResourcerR   s    r   r   z$CloudWildcardIterator._fetch_buckets  s     ../11$))2G2GHH				4#<#< 
	#	#AAII!!
 	

 ,,
!
!))//-- "   !00;<<r   r   returnc              #      K   | j                   j                  | j                  | j                        D ]  }||j                  k(  s|  yw)a  Fetch the soft-deleted buckets with the given name.

      List_buckets retrieves all versions of a bucket, including
      soft-deleted ones. Get_bucket retrieves the live bucket or a specific
      soft-deleted version of the bucket if generation is specified. This is
      useful when needing to access a particular deleted version that has been
      identified from the List_buckets output.

    Args:
      bucket_name (str): Bucket name.

    Yields:
      BucketResource objects.
    r   N)r   r   r   r   r   )rN   r   r   s      r   r.  zCCloudWildcardIterator._fetch_all_soft_deleted_generations_of_bucket  sN     $  <<44''// 5  
,,	,s   AAAc              #     K   t        j                  |      }t        j                  |      }| j                  j                  | j                  | j                        D ]"  }|j                  |j                        s| $ yw)zList buckets matching the wildcard pattern.

    Args:
      bucket_name (str): Bucket name with wildcard.

    Yields:
      BucketResource objects.
    r   N)
r"  r#  rA   r!  r   r   r   r   r   r   )rN   r   regexbucket_patternr   s        r   r-  z5CloudWildcardIterator._list_buckets_matching_wildcard  sr      k*EZZ&N<<44''// 5  
		o22	3s   A:B=Bc                    | j                   t        j                  j                  us0t        j
                  j                  | j                  j                  vry	 | j                  j                  |      }t        t        |dd       xr |j                   j"                        S # t        j                  $ r$}|j                  j                  dk7  r Y d }~yd }~ww xY w)NFi  hierarchicalNamespace)r   r   r   r   r   r   STORAGE_LAYOUTr   r   get_storage_layoutr   r   payloadr   r   rQ   r7  enabled)rN   r   bucket_layoutr  s       r   r   z$CloudWildcardIterator._is_hns_bucket  s    K$=$=$M$MM..dll6O6OO
ll55kBm 6= 	8//77  !! 
 
	"	"c	)s   B" "C5CC)F)#rT   rU   rV   rW   r   r   NO_ACLr   r   r   r   r   r   rO   r   r   r   r   r   r   r  r  r  r   r(  r  r   rk   r   r   BucketResourcer.  r-  r   r   r   s   @r   r6   r6   R  s   I
  $)((//!(==II ..::((--/3 !Un:x"H!F@8 8=$N 8=?B0<Vp$IL,=4"1122"112(r   r6   c                   X    e Zd ZdZd Zeej                  j                  fd       Z	d Z
y)r  zGDifferent parts of the wildcard string used for querying and filtering.c                 <    || _         || _        || _        || _        y)a>  Initialize the CloudWildcardParts object.

    Args:
      prefix (str): The prefix string to be passed to the API request.
        This is the substring before the first occurrance of the wildcard.
      filter_pattern (str): The pattern to be used to filter out the results
        returned by the list_objects call. This is a substring starting from
        the first occurance of the wildcard upto the first delimiter.
      delimiter (str): The delimiter to be passed to the api request.
      suffix (str): The substirng after the first delimiter in the wildcard.
    N)r   r  r   r  )rN   r   r  r   r  s        r   rO   zCloudWildcardParts.__init__  s!     DK(DDNDKr   c                 r    t        |      \  }}|j                  |      \  }}}d|v rd}|}d} | ||||      S )a  Create a CloudWildcardParts instance from a string.

    Args:
      string (str): String that needs to be splitted into different parts.
      delimiter (str): The delimiter to be used for splitting the string.

    Returns:
      WildcardParts object.
    r\   N)_split_on_wildcard	partition)clsstringr   r   wildcard_stringr  _r  s           r   r  zCloudWildcardParts.from_string  sV     18FO !0 9 9) DNAv~ i&nfv~y&99r   c                 ,    t        j                  |       S rj   )r   generic_reprrR   s    r   rS   zCloudWildcardParts.__repr__  s    $$T**r   N)rT   rU   rV   rW   rO   classmethodr   r5   CLOUD_URL_DELIMr  rS   rX   r   r   r  r    s2    O" )4)=)=)M)M : :6+r   r  c                 t    t         j                  |       }|| dfS |j                         }| d| }| |d }||fS )a3  Split the string into two such that first part does not have any wildcard.

  Args:
    string (str): The string to be split.

  Returns:
    A 2-tuple where first part doesn't have any wildcard, and second part does
    have a wildcard. If wildcard is not found, the second part is empty.
    If string starts with a wildcard then first part is empty.
    For example:
      _split_on_wildcard('a/b/c/d*e/f/*.txt') => ('a/b/c/d', '*e/f/*.txt')
      _split_on_wildcard('*e/f/*.txt') => ('', '*e/f/*.txt')
      _split_on_wildcard('a/b/c/d') => ('a/b/c/d', '')
  Nrh   )r   r   start)rE  r   first_wildcard_idxr   wildcard_strs        r   rB  rB    sV     


'%
]2:{{}%%&&*+,,		r   )8rW   
__future__r   r   r   abcr  r"  r   r   rw   rA   typingr   googlecloudsdk.api_lib.storager   r   r	   r   r
   "googlecloudsdk.command_lib.storager9   r   r   ,googlecloudsdk.command_lib.storage.resourcesr   googlecloudsdk.corer   googlecloudsdk.core.utilr   sixrr   r!  rC   r   	frozensetr   ru   r   r    r   r=  r   r   r   r   r   r=   rG   with_metaclassABCMetarI   r8   r6   r  rB  rX   r   r   <module>r\     sf    8 &  ' 
    	  	  6 4 ? A G : : K # 1 
 ? %2::i0 K("CrvvtTBFF]#KL 4	1 "'&&--$&;;GG,,88&&++-2%\G~D K)s))#++6 K0E
+ E
PU
, U
p1+ 1+hr   