
                            S 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KJr  SSKJr  SSKJr  SSKJr  \R@                  " SS5      RC                  SS9r"Sr#Sr$Sr%Sr&Sr'S r( " S  S!\RR                  5      r* " S" S#\RR                  5      r+S$ r,S%\+RZ                  4S& jr.S' r/S( r0S) r1S* r2S+ r3S, r4S- r5S. r6 SAS/ jr7S0 r8S1 r9S2 r:S3\	\;   4S4 jr<S5 r=S6 r>S7 r?S8 r@S9 rAS: rBS; rC SBS< jrD   SCS= jrES> rFS? rGS@ rHg)Dz-Tools for making the most of GcsApi metadata.    )absolute_import)division)unicode_literalsN)List)encoding)encoding_helper)metadata_util)request_config_factory)metadata_field_converters)apis)encryption_util)errors)	gzip_util)storage_url)user_request_args_factory)gcs_resource_reference)resource_reference)resource_util)
propertiesstoragev1PRIVATE_DEFAULT_OBJ_ACL)idtypevalue
createTime
updateTimezno-transformc                 H    U b  [         R                  " U 5      nU/ :X  a  gU$ g)z:Converts message to dict. Returns None is message is None.N)r   MessageToDict)messageresults     <lib/googlecloudsdk/api_lib/storage/gcs_json/metadata_util.py_message_to_dictr#   :   s,    ##G,F |M	    c                       \ rS rSrSrSrSrg)ContextTypeF   zAUsed to distinguish between custom and google generated contexts.CUSTOM N)__name__
__module____qualname____firstlineno____doc__r(   __static_attributes__r)   r$   r"   r&   r&   F   s
    I&r$   r&   c                   (    \ rS rSrSrSrSrSrSrSr	g)	
MethodTypeK   z#Configuration for copying metadata.object_patchobject_rewriteobject_composeobject_insertr)   N)
r*   r+   r,   r-   r.   OBJECT_PATCHOBJECT_REWRITEOBJECT_COMPOSEOBJECT_INSERTr/   r)   r$   r"   r1   r1   K   s    +,#.#.!-r$   r1   c                     [         U 0$ )zaReturns the context value dict based on the value.

Args:
  value (str): The value to be parsed.
)CONTEXT_VALUE_LITERAL)r   s    r"   !get_context_value_dict_from_valuer=   S   s      	''r$   Fc                    U(       ak  UR                   nUR                  n[        R                  " U 5      nXQl         Xal        SUl        SUl        UR                  R                  S:X  a  / Ul        U$ UR                  R                  (       aL  U R                  (       d  [        R                  " S5      e[        R                  " U R                  5      Ul        U R                  Ul        U R                  Ul        U R                  Ul        U R                  Ul        U R                  Ul        U R                   Ul        U R"                  Ul        U R$                  Ul        [        R                  " U R&                  5      Ul        U[(        R*                  :w  a%  [        R                  " U R,                  5      Ul        U$ )a  Copies specific metadata from source_metadata to destination_metadata.

The API manually generates metadata for destination objects most of the time,
but there are some fields that may not be populated.

Args:
  source_metadata (messages.Object): Metadata from source object.
  destination_metadata (messages.Object): Metadata for destination object.
  request_config (request_config_factory.RequestConfig): Holds context info
    about the copy operation.
  should_deep_copy (bool): Copy all metadata, removing fields the
    backend must generate and preserving destination address.
  method_type (MethodType): The type of method being used to copy the object,
      defaulting to MethodType.OBJECT_REWRITE.

Returns:
  New destination metadata with data copied from source (messages.Object).
NFz5Attempting to preserve ACLs but found no source ACLs.)bucketnamecopydeepcopy
generationr   resource_argspreserve_aclaclr   ErrorcacheControlcontentDispositioncontentEncodingcontentLanguagecontentTypecrc32c
customTimemd5Hashmetadatar1   r9   contexts)source_metadatadestination_metadatarequest_configshould_deep_copymethod_typedestination_bucketdestination_names          r"   copy_object_metadatarY   \   sw   . -44+00==9"4 0&*#"##00E9!#6 
3 ##00  llC
 	
 "&/B/B!C(7(D(D%.=.P.P++:+J+J(+:+J+J('6'B'B$"1"8"8&5&@&@##2#:#: $(MM/2J2J$K!j/// '+mmO4L4L&M#	r$   c                 R   [         R                  " SS5      nU R                  5       (       a  UR                  U R                  S9$ U R                  5       (       aM  U R                  (       a  [        U R                  5      OSnUR                  U R                  U R                  US9$ g)zDTakes storage_url.CloudUrl and returns appropriate Apitools message.r   r   )r@   N)r@   r?   rC   )
r   GetMessagesModule	is_bucketBucketbucket_name	is_objectrC   intObjectresource_name)	cloud_urlmessagesrC   s      r"   get_apitools_metadata_from_urlre      s    ##It4(??	 5 5?66.7.B.BY))*J??$$$$    r$   c           
         [         R                  " [         R                  R                  U R                  S9nU R
                  (       a2  U R
                  R                  (       a  U R
                  R                  nOSn[        [        U R                  SS5      SS5      n[        R                  " U40 S[        U R                  5      _S[        U R
                  5      _SU_S[        U R                  5      _S	U R                  _S
[        U R                   5      _S[        U R"                  5      _SU R$                  =(       d    S_S[        U R&                  SS5      _SU R(                  _SU R*                  _S[        U R,                  5      _S[        U R.                  5      _S[        U R0                  5      _SU R2                  _SU R4                  _S[        U R6                  5      _SU _SU R8                  _SU R:                  _S[        U R<                  5      _SU R>                  _S[        U R                  SS5      _S[        U R@                  SS5      _S [        U RB                  5      _S!U RD                  _S"U RF                  _S#[        U RH                  5      _S$U_S%U RJ                  _S&U RL                  _S'U RN                  _S([        U RP                  SS5      _S)[        U RR                  5      _6$ )*zHelper method to generate a BucketResource instance from GCS metadata.

Args:
  metadata (messages.Bucket): Extract resource properties from this.

Returns:
  BucketResource with properties populated by metadata.
)schemer^   NuniformBucketLevelAccessenabledrF   	autoclassautoclass_enabled_timecors_configcreation_timecustom_placement_configdefault_acldefault_event_based_holddefault_kms_keydefaultKmsKeyNamedefault_storage_classetaglabelsip_filter_configlifecycle_configlocationlocation_typelogging_configrP   rC   metagenerationper_object_retentionproject_numberpublic_access_preventionpublicAccessPreventionrequester_paysrequesterPaysretention_policyrposatisfies_pzssoft_delete_policyuniform_bucket_level_accessupdate_timesoft_delete_timehard_delete_timeversioning_enabledwebsite_config)*r   CloudUrlProviderPrefixGCSr@   rj   ri   
toggleTimegetattriamConfigurationr   GcsBucketResourcer#   rF   corstimeCreatedcustomPlacementConfigdefaultObjectAcldefaultEventBasedHold
encryptionstorageClassrt   ru   ipFilter	lifecyclerx   locationTypeloggingrC   r{   objectRetentionprojectNumberbillingretentionPolicyr   satisfiesPZSsoftDeletePolicyupdatedsoftDeleteTimehardDeleteTime
versioningwebsite)rP   urlrk   r   s       r"   !get_bucket_resource_from_metadatar      s    	''++	H# H..66%//::! 'h'')CTJ! 
 	1	1	&

8<<
(&
 !!3!34&
 4	&

 #8==1&
 ((&
 /x/M/MN&
 #8#<#<=&
  (==E&
 h113FM&
 %11&
 ==&
 hoo.&
 ((9(9:&
 ((:(:;&
    !&
" ))#&
$ &h&6&67%&
& '&
( $$)&
* ,,+&
, ,H,D,DE-&
. ++/&
0  '

#
#%=t 1&
6 X--E7&
8 ((@(@A9&
: ,,;&
< ))=&
> *(*C*CD?&
@ #>A&
B ""C&
D  ..E&
F  ..G&
H !!4!4iFI&
J &h&6&67K&
 &r$   c                    [         R                  " SS5      nUR                  U R                  U R                  U R
                  U R                  S9nU R                  (       a(  UR                  R                  U R                  S9Ul	        U R                  (       aI  UR                  R                  UR                  R                  R                  U R                  S9S9Ul        U$ )zHelper method to generate Apitools metadata instance from BucketResource.

Args:
  resource (BucketResource): Extract metadata properties from this.

Returns:
  messages.Bucket with properties populated by resource.
r   r   )r@   rt   rx   r   )retentionPeriod)ri   )rh   )r   r[   r]   r@   rt   rx   rs   retention_periodRetentionPolicyValuer   r   IamConfigurationValueUniformBucketLevelAccessValuer   )resourcerd   rP   s      r"   !get_metadata_from_bucket_resourcer      s     ##It4(__====  11	  3( 'CC 11  D  3H)) ( E E!)!F!F	&	&88 
' 
: !F !;H
 
/r$   c                    [         R                  " [         R                  R                  U R                  U R
                  S9n[        R                  " U R                  U R
                  U R                  U R                  U R                  U R                  U U R                  U R                  UU R                  U R                  U R                   S9$ )Nrg   r^   rb   )admission_policyanywhere_cache_idr?   create_time	id_stringkindrP   pending_updatestater   ttlr   zone)r   r   r   r   r?   anywhereCacheIdr   GcsAnywhereCacheResourceadmissionPolicyr   r   r   pendingUpdater   r   r   r   rP   r   s     r"   )get_anywhere_cache_resource_from_metadatar     s    ''++//,,	#
 
 	8	8// 00__%%==++NN
,,%%==
 r$   c                 
   U c  U $ 0 nU R                  5        H^  u  p#UR                  [        S5      nUR                  [        S5      nU[        R
                  R                  :X  d  MQ  [        U5      X'   M`     [        U5      $ )a  Parses custom contexts from resource contexts for request purposes.

Examples:
  resource_contexts_dict={
      'key': {
          'value': 'value',
          'createTime': '2025-01-01T00:00:00Z',
          'updateTime': '2025-01-01T00:00:00Z',
          'type': 'CUSTOM'
      }
      'key2': {
          'value': 'value2',
          'createTime': '2025-01-01T00:00:00Z',
          'updateTime': '2025-01-01T00:00:00Z',
          'type': 'GENERATED'
      }
  } would return the following dictionary:
  {
      'custom': {
        'key': {
            'value': 'value',
        }
      }
  }

Note: the method intentionally drops all other fields other than the context
value, as they are internal only fields, or not meant to be sent to the API.

Args:
  resource_contexts_dict (dict): The resource contexts dict to parse.

Returns:
  a dictionary of contexts in apitools format for request purposes.
N)	itemsgetCONTEXT_TYPE_LITERALr<   r&   r(   r   r=   +get_contexts_dict_from_custom_contexts_dict)resource_contexts_dictcustom_contexts_dictkeyr   context_typecontext_values         r"   6parse_custom_contexts_dict_from_resource_contexts_dictr     s    J #!!*002jc99148LII3T:M{))///
+M
: 	 3 
55I	JJr$   c                    U R                   (       a  U R                   R                  (       d  g[        U R                   R                  5      n0 nUR                  5        H  u  p40 n[        [
        4 HA  nXd;   d  M
  [        R                  " [        R                  R                  XF   5      5      XV'   MC     U[           U[        '   [        R                  R                  U[        '   XRU'   M     U$ )a  Returns parsed contexts from apitools object metadata.

apitools object metadata separates custom contexts, and google generated
contexts (coming in 2026) into separate maps, However CLI along with other
clients uses a single map with a type field to distinguish between the two.
This method parses the apitools object metadata into the single map format
used by CLI and other clients.

Args:
  metadata (messages.Object): The object metadata to parse contexts from.
N)rQ   customr#   r   CONTEXT_CREATE_TIME_LITERALCONTEXT_UPDATE_TIME_LITERALr   )get_formatted_string_from_datetime_objectdatetimefromisoformatr<   r&   r(   r   r   )rP   custom_contextsparsed_contextsr   r   context_value_dictfields          r"   $_parse_contexts_from_object_metadatar   M  s     

 1 1 8 8$X%6%6%=%=>//#))+jc-/JK	CC!!//= 	! L 166K0L,-/:/A/A/G/G+,-C , 
r$   c                    U R                   b  [        U R                   5      nOSn[        R                  " [        R                  R
                  U R                  U R                  US9nU R                  (       a-  U R                  R                  nU R                  R                  nOS=p4[        R                  " U40 S[        U R                  5      _SU R                  _SU R                   _SU R"                  _SU R$                  _SU R&                  _S	U R(                  _S
U R*                  _SU R,                  _S[/        U 5      _S[        U R0                  5      _SU R2                  _SU_SU_SU R4                  _SU R6                  (       a  U R6                  OS_SU R8                  _SU R:                  _SU R<                  _SU _SU R>                  _SU R@                  _SU RB                  _S[        U RD                  5      _SU RF                  _SU RH                  _SU RJ                  _SU RL                  _SU RN                  (       a  U RN                  OS_S U RP                  _6$ )!zHelper method to generate a ObjectResource instance from GCS metadata.

Args:
  metadata (messages.Object): Extract resource properties from this.

Returns:
  ObjectResource with properties populated by metadata.
N)rg   r^   rb   rC   rF   cache_controlcomponent_countcontent_dispositioncontent_encodingcontent_languagecontent_typecrc32c_hashrm   rQ   custom_fieldscustom_timedecryption_key_hash_sha256encryption_algorithmrt   event_based_holdr   kms_keymd5_hashrP   r{   noncurrent_timeretention_expirationretention_settingssizer   storage_classstorage_class_update_timetemporary_holdr   ))rC   strr   r   r   r   r?   r@   customerEncryption	keySha256encryptionAlgorithmr   GcsObjectResourcer#   rF   rH   componentCountrI   rJ   rK   rL   rM   r   r   rP   rN   rt   eventBasedHoldr   
kmsKeyNamerO   r{   timeDeletedretentionExpirationTime	retentionr   r   r   timeStorageClassUpdatedtemporaryHoldr   )rP   rC   r   r   r   s        r"   !get_object_resource_from_metadatar   m  s    $X(()JJ''++//MM		#   !)!<!<!F!F#66JJ8<<		1	1	"

8<<
("
 ))"
 --	"

 #55"
  //"
  //"
 ''"
 //"
 (("
 4H="
 %X%6%67"
 %%"
 "<"
 0"
  ==!"
$ &.%<%<(
!
!$%"
(  ..)"
* !!+"
, -"
. /"
0 ,,1"
2 **3"
4 $;;5"
6 *(*<*<=7"
8 ==9"
:  ..;"
< ))="
> !) @ @?"
@ 08/E/EX++4A"
B ""C"
 "r$   c                    U Vs0 s H  o"R                  5       U_M     nnU R                  (       a#  U R                  R                  5       nXC;   a  X4   $ U R                  (       a#  U R                  R                  5       nXS;   a  X5   $ U R                  (       a#  U R                  R                  5       nXc;   a  X6   $ U R                  (       aQ  SR                  U R                  R                  U R                  R                  5      R                  5       nXs;   a  X7   $ U R                  (       a+  U R                  R                  5       nX;   a  US;   a  X8   $ gggs  snf )a  Shim-only support for case-insensitive matching on non-entity metadata.

Ports the logic here:
https://github.com/GoogleCloudPlatform/gsutil/blob/0d9d0175b2b10430471c7b744646e56210f991d3/gslib/utils/acl_helper.py#L291

Args:
  existing_grant (BucketAccessControl|ObjectAccessControl): A grant currently
    in a resource's access control list.
  grant_identifiers (Iterable[str]): User input specifying the grants to
    remove.

Returns:
  A string matching existing_grant in grant_identifiers if one exists.
    Otherwise, None. Note that this involves preserving the original case of
    the identifier, despite the fact that this function performs a
    case-insensitive comparison.
z{}-{})allusersallauthenticatedusersN)	lowerentityIdemaildomainprojectTeamformatteamr   entity)	existing_grantgrant_identifiers
identifier!normalized_identifier_to_originalnormalized_entity_idnormalized_emailnormalized_domainnormalized_identifiernormalized_entitys	            r"   1_get_matching_grant_identifier_to_remove_for_shimr    sT   . 8I'7H*$7H $ ' )2288:@.DD%++113<.@@&--335=.AA&&++&&44	
 eg  A.EE&--335>!FF.AA G 	? ;'s   Ec           	         / nU(       a4  [        UR                  =(       d    / 5      nUR                  =(       d    / nO3[        UR                  =(       d    / 5      nUR                  =(       d    / n[        S U 5       5      nU Vs0 s H  oS_M     n	nU  H  n
[
        R                  R                  R                  R                  5       (       a  [        X5      nOU
R                  U;   a  U
R                  nOSnX;   a  SX'   Mp  U
R                  U;  d  M  UR                  U
5        M     U	R                  5        VVs/ s H  u  pU(       a  M  UPM     nnnU(       a.  [        R                  " SR!                  [#        U5      5      5      e[$        R&                  " U5      nU H7  nUR                  U" UR)                  S5      UR)                  S5      S95        M9     U$ s  snf s  snnf )	a  Returns shallow copy of ACL policy object with requested changes.

Args:
  acl_list (list): Contains Apitools ACL objects for buckets or objects.
  resource_args (request_config_factory._ResourceConfig): Contains desired
    changes for the ACL policy.
  is_bucket (bool): Used to determine if ACL for bucket or object. False
    implies a cloud storage object.
  is_default_object_acl (bool): Used to determine if target is default object
    ACL list.

Returns:
  list: Shallow copy of acl_list with added and removed grants.
c              3   *   #    U  H	  oS    v   M     g7f)r	  Nr)   ).0grants     r"   	<genexpr>>_get_list_with_added_and_removed_acl_grants.<locals>.<genexpr>  s     N<M5X<Ms   FNTzAACL entities marked for removal did not match existing grants: {}r	  role)r	  r  )set#default_object_acl_grants_to_remove default_object_acl_grants_to_addacl_grants_to_removeacl_grants_to_addr   VALUESr   run_by_gsutil_shimGetBoolr  r	  appendr   r   rG   r  sortedr   get_bucket_or_object_acl_classr   )acl_listrD   r\   is_default_object_aclnew_acl_listacl_identifiers_to_remover  acl_identifiers_to_addr  found_matchr
  matched_identifierkvunmatched_entities	acl_class	new_grants                    r"   +_get_list_with_added_and_removed_acl_grantsr2    s   " , #99?R! &FFL" #M$F$F$L" M%77=2N<MNN5NO5NzU"5N+O n  33;;==L
 
		";	;)00((,k% 
		&<	<.)' !* '2&7&7&9C&9da&9C
,,	fV./0 
 (FF) %ix0y}}V7LM %
 
K P, Ds   G%G*G*c                 ~   [         R                  " SS5      nU (       a  U R                  nO/ n/ n[        UR                  =(       d    / 5      nU Hc  nUR
                  U;   a?  UR                  UR                  R                  R                  UR
                  SS95        MR  UR                  U5        Me     UR                  =(       d    0 nUR                  5        H7  u  pUR                  UR                  R                  R                  XS95        M9     U (       d  U(       d  gUR                  R                  US9$ )a  Returns shallow copy of bucket labels object with requested changes.

Args:
  labels_object (messages.Bucket.LabelsValue|None): Existing labels.
  resource_args (request_config_factory._BucketConfig): Contains desired
    changes for labels list.

Returns:
  messages.Bucket.LabelsValue|None: Contains shallow copy of labels list with
    added and removed values or None if there was no original object.
r   r   N)r   r   )additionalProperties)r   r[   r4  r  labels_to_remover   r#  r]   LabelsValueAdditionalPropertylabels_to_appendr   )
labels_objectrD   rd   existing_labels
new_labelsr5  existing_labelr8  r   r   s
             r"   0_get_labels_object_with_added_and_removed_labelsr=  -  s    ##It4(#88OO*77=2>'n--
//
%
%
8
8 $$D 9 23 ' ( #339r$**,jc##6636LN - :		$	$*	$	EEr$   c                 	   [        USS5      nU(       d  gUR                  c  UR                  b0  [        R                  " UR                  UR                  5      U l        UR                  b%  [        R                  " UR                  5      U l        UR                  b%  [        R                  " UR                  5      U l        UR                  b%  [        R                  " UR                  5      U l        UR                  b  UR                  U l        UR"                  b%  [        R$                  " UR"                  5      U l        UR(                  b%  [        R*                  " UR(                  5      U l        UR.                  b%  [        R0                  " UR.                  5      U l        UR4                  b  UR4                  U l        UR6                  c  UR8                  b;  [        R:                  " U R<                  UR6                  UR8                  5      U l        UR@                  b%  [        RB                  " UR@                  5      U l"        URF                  c  URH                  b;  [        RJ                  " U RL                  URF                  URH                  5      U l&        URN                  b  URN                  U l(        URR                  b0  [        RT                  " U RV                  URR                  5      U l+        URX                  b%  [        RZ                  " URX                  5      U l.        UR^                  b%  [        R`                  " UR^                  5      U l1        URd                  b%  [        Rf                  " URd                  5      U l2        URh                  c  URj                  b0  [        Rl                  " URh                  URj                  5      U l7        URp                  b$  [        Rr                  " URp                  SS9U l:        [w        U Rt                  USSS9U l:        URx                  b$  [        Rr                  " URx                  SS9U l=        [w        U Rz                  USSS9U l=        UR|                  b0  [        R~                  " U R                  UR|                  5      U l@        [        U R                  U5      U l@        g)z>Sets Apitools Bucket fields based on values in request_config.rD   NTr\   F)r\   r'  )Br   enable_autoclass autoclass_terminal_storage_classr   process_autoclassrj   enable_hierarchical_namespaceprocess_hierarchical_namespacehierarchicalNamespacecors_file_pathprocess_corsr   default_encryption_keyprocess_default_encryption_keyr   rp   r   rs   process_default_storage_classr   ip_filter_file_pathprocess_ip_filterr   lifecycle_file_pathprocess_lifecycler   rx   
log_bucketlog_object_prefixprocess_log_configr@   r   	placementprocess_placement_configr   r~   r    process_bucket_iam_configurationr   recovery_point_objectiver   r   process_requester_paysr   r   process_retention_periodr   soft_delete_durationprocess_soft_delete_durationr   r   process_versioningweb_error_pageweb_main_page_suffixprocess_websiter   acl_file_pathprocess_acl_filerF   r2  default_object_acl_file_pathr   labels_file_pathprocess_labelsru   r=  )bucket_metadatarT   rD   s      r"   *update_bucket_metadata_from_request_configrd  W  sZ   ./4@-	
 $$0		7	7	C 9 K K&&66!O 00<!@@77	
 )
 !!-4AA$$&O))5!@@00	2  ++7.. )((4!??//	1   ''38JJ)) O &&2!33--	/  ',55O*%%17JJm66'')O (!::##	% ) ,,8//; 	"BB,,2255	7 $
 ++7'@@O!!-!88##]%A%A	C  ##/!::**	, # ''3!>>..	
 $
 )!44$$	&  "".((47GG$$m&H&HJO   ,3DD##tO 2



 %	'  //;!2266%	
 $ 2

*
*
 $	& " ##/6EE > >@O Lm-/r$   c                    / n[        U SS5      nU(       d  U$ UR                  [        R                  :X  d6  UR                  (       a6  [        R
                  " UR                  5      (       d  UR                  S5        UR                  [        R                  :X  a  UR                  S5        UR                  [        R                  :X  a  UR                  S5        UR                  [        R                  :X  a  UR                  S5        UR                  [        R                  :X  d6  UR                  (       a6  [        R
                  " UR                  5      (       d  UR                  S5        UR                  [        R                  :X  a  UR                  S5        O/UR                  [        R                  :X  a  UR                  S	5        UR                  [        R                  :X  a  UR                  S
5        UR                  [        R                  :X  a  UR                  S5        UR                  UR                   s=:X  a  [        R                  :X  a  O  OUR                  S5        U$ UR                  [        R                  :X  a  UR                  S5        U$ UR                   [        R                  :X  a  UR                  S5        U$ )EGets a list of fields to be included in requests despite null values.rD   Nr   r   r   ru   r   r   zlogging.logObjectPrefixz'iamConfiguration.publicAccessPreventionr   r   zwebsite.notFoundPagezwebsite.mainPageSuffix)r   rF  r   CLEARr	   cached_read_yaml_json_filer#  rH  rs   ra  rM  rO  rP  r~   r   r[  r\  rT   cleared_fieldsrD   s      r"   get_cleared_bucket_fieldsrk    sG   ../4@-	 ""&?&E&EE		%	%66

&
& 
 &!))-F-L-LL,'((,E,K,KK.)##'@'F'FF(# ''+D+J+JJ		*	*66

+
+ 
 +&!:!@!@@)$&&*C*I*II34++/H/N/NNCD##'@'F'FF+, ""		+	+)	"	(	() )$ 
 ##'@'F'FF01 
 ))-F-L-LL23	r$   returnc                 :   / nU R                   c  UR                  S5        U R                  c  UR                  S5        O9U R                  b,  U R                  R                  (       d  UR                  S5        U R                  (       d  UR                  S5        U$ )zReturns cleared IP filter fields for the bucket.

Args:
  ip_filter: IP filter object.

Returns:
  List of IP filter fields to be cleared.
zipFilter.modezipFilter.publicNetworkSourcez0ipFilter.publicNetworkSource.allowedIpCidrRangeszipFilter.vpcNetworkSources)moder#  publicNetworkSourceallowedIpCidrRangesvpcNetworkSources)	ip_filterrj  s     r"   get_cleared_ip_filter_fieldsrs    s     .^^/*""*89##/++??LM		$	$67	r$   c                     [        U[        R                  5      (       a  UR                  nOSnU (       a  Uc  [        $ SR                  U[        5      $ U$ )ah  Returns cache control metadata value.

If should_gzip_locally is True, append 'no-transform' to cache control value
with the user's given value.

Args:
  should_gzip_locally (bool): True if file should be gzip locally.
  resource_args (request_config_factory._ObjectConfig): Holds settings for a
    cloud resource.

Returns:
  (str|None) Cache control value.
Nz{}, {})
isinstancer
   _ObjectConfigr   _NO_TRANSFORMr  )should_gzip_locallyrD   user_cache_controls      r"   get_cache_controlrz  '  s]     5CCDD&44 % 	 __/? 
r$   c                 j    U (       a  g[        U[        R                  5      (       a  UR                  $ g)a1  Returns content encoding metadata value.

If should_gzip_locally is True, return gzip.

Args:
  should_gzip_locally (bool): True if file should be gzip locally.
  resource_args (request_config_factory._ObjectConfig): Holds settings for a
    cloud resource.

Returns:
  (str|None) Content encoding value.
gzipN)ru  r
   rv  r   )rx  rD   s     r"   get_content_encodingr}  D  s-     5CCDD)))	r$   c                     [        U [        R                  5      (       a5  [        R                  " UR
                  U R                  R                  5      $ g)NF)ru  r   FileObjectResourcer   rx  gzip_settingsr   rb   )attributes_resourcerT   s     r"   get_should_gzip_locallyr  Z  sG    #%7%J%JKK(($$''55 
 
r$   c                 f    U[         R                  :X  a  [        XS5        gUb  [        XU5        gg)z)Sets appropriate metadata based on value.N)r   rg  setattr)rP   r   r   s      r"   process_value_or_clear_flagr  d  s0    
'---H4 H5! r$   c                 V    [         R                  R                  R                  5       U 0$ )z0Returns contexts dict from custom contexts dict.)r&   r(   r   r  )r   s    r"   r   r   l  s#    



"
"
(
(
*,@	AAr$   c                     [         R                  " SS5      n[        R                  " U 5      n0 nUR	                  5        HN  u  pE[        U[        5      (       a
  [        U;  a  [        R                  " S5      e[        U[           5      X4'   MP     [        R                  " X1R                  R                  R                  5        U$ ! [        R                   ["        4 a    [        R                  " S5      ef = f)aD  Parses custom contexts from a file, and validate it against the message.

Args:
  file_path (str): Path to the file containing the custom contexts.

Returns:
  A dictionary containing the custom contexts parsed from the file.

Raises:
  errors.Error: If the provided file doesn't exist or is not a valid
    json/yaml file.
r   r   z+Invalid format for specified contexts file.zgError while parsing the specified contexts file, please ensure that specified file exists and is valid.)r   r[   r	   rh  r   ru  dictr<   r   rG   r=   r   DictToMessagera   ContextsValueCustomValueInvalidUrlErrorAttributeError)	file_pathrd   parsed_custom_contextsextracted_custom_contextsr   r   s         r"   parse_custom_contexts_from_filer  q  s     %%i6H*EE !#,224
%%"%/llHII ,)*  $ 5 !!!??#@#@#L#L %$

 
 .	1 
,,	/ s   CC	 	1C:c                 .   UR                   nU(       a3  UR                  (       dN  UR                  (       d=  UR                  (       d,  U[        R
                  :w  a  [        R                  " U 5      $ S$ UR                  [        R                  :X  a  0 $ UR                  (       a  [        UR                  [        5      (       a  [        UR                  5      nO8UR                  R                  5        VVs0 s H  u  pVU[        U5      _M     nnnU[        R
                  :w  a  U$ U  Vs0 s H  ow0 _M     nnUR                  " S0 UD6  U$ U[        R
                  :w  a  [        R                  " U 5      O0 nUR                  (       a?  UR                   H/  nU[        R
                  :X  a  0 X'   M  UR!                  US5        M1     UR                  (       a0  UR                  R                  5        H  u  pV[        U5      X'   M     U$ s  snnf s  snf )a  Returns a dictionary with updated custom contexts based on a merge strategy.

Args:
  existing_custom_contexts (dict): Existing custom contexts for an object.
  request_config (request_config): May contain custom contexts fields that
    should be modified.
  method_type (MethodType): method_type for which the custom contexts are
    being updated.

Returns:
  A dictionary containing the updated custom contexts, or None if no updates
  are needed.
Nr)   )rD   custom_contexts_to_setcustom_contexts_to_removecustom_contexts_to_updater1   r7   rA   rB   r   rg  ru  r   r  r   r=   updatepop)	existing_custom_contextsrT   rV   rD   r  r   r   elemupdated_custom_contextss	            r"   get_updated_custom_contextsr    s   $ !..-	**		0	0		0	0 *111 	./  ))-F-L-LLI))-66<<>

.
.  *@@FFH Hjc 07
7H   
 j---## 5MM4LDRx4LM""<%;<"" 

//	/ mm,-  ,,66	
//	/ (*$ 	 ##C. 7 ,,#==CCE

+E
2 " F
 
! I  Ns   6H+Hc                 b   U R                   (       a  U R                   R                  (       d  0 nO*[        R                  " U R                   R                  5      nU(       d  [        R
                  nO:[        U[        5      (       d%  [        R                  " SR                  U5      5      e[        R                  " SS5      n[        X1U5      nU[        R
                  :w  a	  U(       d  SnUb:  [        R                  " [        U5      UR                  R                   5      U l         gSU l         g)a  Updates custom contexts in object_metadata based on request_config.

Args:
  object_metadata (storage_v1_messages.Object): Existing object metadata.
  request_config (request_config): May contain custom contexts fields that
    should be modified.
  method_type (MethodType): Different API methods have different metadata
    handling. for example, objects.rewrite handles contexts updates in one
    way, while objects.patch handles contexts updates in another way. This
    variable is tune the handling of metadata updates based on the API method.
    If invalid an error will be thrown, if None, the default handling
    would be used (object.patch behavior)

Raises:
  errors.Error: If the method type is not supported.
z9Unsupported method type for updating custom contexts: {}.r   r   N)rQ   r   r   r   r1   r7   ru  r   rG   r  r   r[   r  r  r   ra   r  )object_metadatarT   rV   r  rd   r   s         r"   *update_custom_contexts_from_request_configr    s    * 
	!	!)A)A)H)H!.<<  ''  
))Kk:..
,,CJJ	
  ##It4(4 J+++4H%.<<34HI%% O
  $Or$   c                    UR                   nU R                  (       d  0 nO [        R                  " U R                  5      n[        R
                  " UUUUS9nUbF  [        R                  " SS5      n[        R                  " XxR                  R                  5      U l        [        XU5        [        X!5      n	[        X5      n
[        U SU
5        [        X5      n[        U SU5        U(       d  gUR                   (       a  UR                   ["        R$                  :X  d1  UR                   R&                  [(        R*                  R,                  L a  SU l        SU l        OLUR                   R&                  [(        R*                  R2                  L a  UR                   R4                  U l        [        U SUR6                  5        [        U SUR8                  5        [        U S	UR:                  5        [        U S
UR<                  5        [        U SUR>                  5        [        U SUR@                  5        URB                  b%  [D        RF                  " URB                  5      U l$        [K        U RH                  USS9U l$        URL                  b  URL                  U l'        URP                  b  URP                  U l)        [D        RT                  " U RV                  URX                  URZ                  5      U l+        g)a  Sets Apitools Object fields based on values in request_config.

User custom metadata takes precedence over preserved POSIX data.
Gzip metadata changes take precedence over user custom metadata.

Args:
  object_metadata (storage_v1_messages.Object): Existing object metadata.
  request_config (request_config): May contain data to add to object_metadata.
  attributes_resource (Resource|None): If present, used for parsing POSIX and
    symlink data from a resource for the --preserve-posix and/or
    --preserve_symlink flags. This value is ignored unless it is an instance
    of FileObjectResource.
  posix_to_set (PosixAttributes|None): Set as custom metadata on target.
  method_type (MethodType|None): Different API methods have different metadata
    handling, for example, objects.rewrite handles contexts updates in one
    way, while objects.patch handles contexts updates in another way. This
    variable is tune the handling of metadata updates based on the API method.
    If invalid, an error will be thrown. If None, the default handling
    would be used for each metadata field.

Raises:
  errors.Error: If the method type is not supported.
)r  known_posixNr   r   rH   rJ   rI   rK   rN   rL   rO   r   Fr?  ).rD   rP   r   r   r	   get_updated_custom_fieldsr   r[   r  ra   MetadataValuer  r  rz  r  r}  encryption_keyr   rg  r   r   KeyTypeCSEKr   r   CMEKr   r   r   r   r   r   r   r^  r   r_  rF   r2  r   r   r   r   process_object_retentionr   retain_untilretention_mode)r  rT   r  posix_to_setrV   rD   existing_metadatacustom_fields_dictrd   rx  r   r   s               r"   *update_object_metadata_from_request_configr  %  s   < !..- 
	!	!'55  " %>>-	 #%%i6H.<<OO99 ;O -{ 0+ $$7G-o~}M)*=Mo/@.0 

 !!$$(A(G(GG$$))_-D-D-I-II#'o +/o(		%	%	*	*o.E.E.J.J	J#0#?#?#C#Co  +]-N-N (-*H*H |]%>%> }m&@&@ y-"8"8 ~}'B'B   ,3DD##O D=E/ ##/%2%C%CO"!!-$1$@$@O!  88

#
#

$
$

&
& r$   c                    / nU R                   nU(       d  U$ UR                  [        R                  :X  a  UR	                  S5        UR
                  [        R                  :X  a  UR	                  S5        UR                  [        R                  :X  a  UR	                  S5        UR                  [        R                  :X  a  UR	                  S5        UR                  [        R                  :X  a  UR	                  S5        UR                  [        R                  :X  a  UR	                  S5        UR                  [        R                  :X  d  UR                  [        R                  :X  a  UR	                  S5        U$ )rf  rH   rL   rI   rJ   rK   rN   r   )rD   r   r   rg  r#  r   r   r   r   r   r  r  ri  s      r"   get_cleared_object_fieldsr    s0   . ..-	  $=$C$CC.)#<#B#BB-(&&*C*I*II./##'@'F'FF+,##'@'F'FF+,";"A"AA,'   $=$C$CC		%	%)B)H)H	H+&	r$   c                     [         R                  " [         R                  R                  U R                  U R
                  S9n[        R                  " UU R                  U U R                  U R                  S9$ )z7Returns a ManagedFolderResource from Apitools metadata.r   r   rP   r{   r   )r   r   r   r   r?   r@   r   ManagedFolderResourcer   r{   r   r   s     r"   )get_managed_folder_resource_from_metadatar    se    ''++//MM	#
 
	1	1	%%,,%%
 r$   c                     [         R                  " [         R                  R                  U R                  U R
                  S9n[        R                  " UU R                  U U R                  U R                  S9$ )z0Returns a FolderResource from Apitools metadata.r   r  )r   r   r   r   r?   r@   r   FolderResourcer   r{   r   r   s     r"   !get_folder_resource_from_metadatar    se    ''++//MM	#
 
	*	*	%%,,%%
 r$   )FF)N)NNN)Ir.   
__future__r   r   r   rA   r   enumtypingr   apitools.base.pyr   r   googlecloudsdk.api_lib.storager	   r
   'googlecloudsdk.api_lib.storage.gcs_jsonr   googlecloudsdk.api_lib.utilr   "googlecloudsdk.command_lib.storager   r   r   r   r   ,googlecloudsdk.command_lib.storage.resourcesr   r   r   googlecloudsdk.corer   r[   ObjectAccessControlPRIVATE_DEFAULT_OBJECT_ACLr   r<   r   r   rw  r#   Enumr&   r1   r=   r8   rY   re   r   r   r   r   r   r   r  r2  r=  rd  rk  r   rs  rz  r}  r  r  r   r  r  r  r  r  r  r  r)   r$   r"   <module>r     s   4 &  '     % , 8 A M , > 5 8 : H O K F * "33t((,E(F   * * 	$)) 
" "( +0%/%>%>	>B
;|8./Kd@<~9Bz EJBJ'FTv-r:z	#Y4:,"B
-`L!d 2$p upD r$   