
    \                        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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dZdZej>                  j@                  eej>                  jB                  eej>                  jD                  eiZ#dZ$dZ%dZ&dZ'dZ( G d dejR                        Z*ej>                  j@                  fdZ+ej>                  j@                  fdZ,ej>                  j@                  ddfdZ-d Z.d Z/d  Z0d! Z1d" Z2d# Z3d6d$Z4d% Z5d& Z6	 	 d7d'Z7	 	 d7d(Z8	 	 d7d)Z9	 d6d*Z:	 d6d+Z;d, Z<d- Z=d. Z>d8d/Z?d8d0Z@d1 ZAd2 ZBd3 ZCd4 ZDd5 ZEy)9z!Utilities for the cloudbuild API.    )absolute_import)division)unicode_literalsN)messages)encoding)cloudbuild_exceptions)apis)base)
exceptions)yaml)resource_property)files
cloudbuildv1v1beta1z'projects/.*/locations/.*/workerPools/.*z)projects/.*/locations/.*/workerPools/(.*)z)projects/.*/locations/(.*)/workerPools/.*globali   @c                       e Zd ZdZdZdZy)WorkerpoolTypesr         N)__name__
__module____qualname__UNKNOWNPRIVATEHYBRID     8lib/googlecloudsdk/api_lib/cloudbuild/cloudbuild_util.pyr   r   8   s    ''&r   r   c                 D    t        j                  t        t        |          S )zReturns the messages module for Cloud Build.

  Args:
    release_track: The desired value of the enum
      googlecloudsdk.calliope.base.ReleaseTrack.

  Returns:
    Module containing the definitions of messages for Cloud Build.
  )r	   GetMessagesModule	_API_NAMERELEASE_TRACK_TO_API_VERSIONrelease_tracks    r   r!   r!   >   s#     
			 <] K
M Mr   c                 D    t        j                  t        t        |          S )zReturns the client class for Cloud Build.

  Args:
    release_track: The desired value of the enum
      googlecloudsdk.calliope.base.ReleaseTrack.

  Returns:
    base_api.BaseApiClient, Client class for Cloud Build.
  )r	   GetClientClassr"   r#   r$   s    r   r'   r'   L   s#     
		Y9-H
J Jr   TFc                 L    t        j                  t        t        |    | |      S )a  Returns an instance of the Cloud Build client.

  Args:
    release_track: The desired value of the enum
      googlecloudsdk.calliope.base.ReleaseTrack.
    use_http: bool, True to create an http object for this client.
    skip_activation_prompt: bool, True to skip prompting for service activation.
      Should be used only if service activation was checked earlier in the
      command.

  Returns:
    base_api.BaseApiClient, An instance of the Cloud Build client.
  )no_httpskip_activation_prompt)r	   GetClientInstancer"   r#   )r%   use_httpr*   s      r   r+   r+   Z   s*    $ 
		"=1|3	
 r   c                 `    | sy t        j                  | |j                  j                  d      S )NT)
sort_items)apitools_encodingDictToAdditionalPropertyMessageBuildSubstitutionsValue)substitutionsr   s     r   EncodeSubstitutionsr4   t   s.    			:	:X^^664
I Ir   c                     | sy g }t        t        j                  |             D ]'  \  }}|j                  |j	                  ||             )  ||      S )NkeyvalueadditionalProperties)sortedsix	iteritemsappendAdditionalProperty)r3   
value_typesubstitution_propertiesr7   r8   s        r   EncodeTriggerSubstitutionsrB   |   sY    	3==78jc5""%%#U%;= 9 
)@	AAr   c                    |s| S i }| r*| j                   D ]  }|j                  ||j                  <    t        j                  |      D ]
  \  }}|||<    g }t        |j                               D ];  \  }}|j                  |j                  j                  j                  ||             = |j                  j                  |      S )a6  Encodes the trigger substitutions for the update command.

  Args:
    old_substitutions: The existing substitutions to be updated.
    substitutions: The substitutions to be added to the existing substitutions.
    messages: A Cloud Build messages module.

  Returns:
    The updated trigger substitutions.
  r6   r9   )r:   r8   r7   r<   r=   r;   itemsr>   BuildTriggerr2   r?   )old_substitutionsr3   r   substitution_mapsubr7   r8   updated_substitutionss           r   !EncodeUpdatedTriggerSubstitutionsrJ      s     
 55"%))sww 6 MM-0jc5!S 1 +1134jc5  00CC5 	D 	
 5 
			1	10 
2 
 r   c                    |syg }| rj| j                   D ][  }|j                  |vs|j                  |j                  j                  j                  |j                  |j                               ] |s3|j                  |j                  j                  j                                |j                  j	                  |      S )a   Removes existing substitutions for the update command.

  Args:
    old_substitutions: The existing substitutions.
    substitutions_to_be_removed: The substitutions to be removed if exist.
    messages: A Cloud Build messages module.

  Returns:
    The updated trigger substitutions.
  Nr6   r9   )r:   r7   r>   rE   r2   r?   r8   )rF   substitutions_to_be_removedr   rA   rH   s        r   RemoveTriggerSubstitutionsrM      s     
% 55	3	3&&!!44GGGG399 H 	
 6 
!""00CCE 
			1	12 
2 
 r   c                     | j                   j                  j                         g}| j                   j                  |      S )Nr9   )rE   r2   r?   )r   rA   s     r   EncodeEmptyTriggerSubstitutionsrO      sE    ..AAC 
			1	12 
2 
 r   c                    | j                  d      }|s| S d}|D ]  }|s|dz  } n |r||d }|sd|dz
  z  S d|z  |d   z   |d<   dj                  |dd |dd D cg c]  }|j                          c}z         S c c}w )zChange a snake_case string into a camelCase string.

  Args:
    snake: str, the string to be transformed.

  Returns:
    str, the transformed string.
  _r   r   N )splitjoin
capitalize)snakepartsleading_blankspss        r   SnakeToCamelStringr[      s     ++c
%	L
 .an	 
 ./"E NQ&''^#eAh.E!H	reABi@iallni@@	AA@s   A=
c           	         |g }t        | t              rBt        j                  |       D ci c]!  \  }}t	        |      ||vrt        ||      n|# c}}S t        | t              r| D cg c]  }t        ||       c}S | S c c}}w c c}w )a  Recursively transform all keys and values from snake_case to camelCase.

  If a key is in skip, then its value is left alone.

  Args:
    msg: dict, list, or other. If 'other', the function returns immediately.
    skip: contains dict keys whose values should not have camel case applied.

  Returns:
    Same type as msg, except all strings that were snake_case are now CamelCase,
    except for the values of dict keys contained in skip.
  )
isinstancedictr<   r=   r[   SnakeToCamellist)msgskipr7   valelems        r   r_   r_      s     
\DT c* +HC 	3$'tOc4	 	=* 
 #t145Lt$55J 6s   &B+B	c                    g }| j                         D ]  }| j                  |j                        }|j                  r|s-|0|j                  dk(  rd}n1|j                  dk(  rd}nt	        j
                  |j                        }t        |d      r2t        |      D ]#  }|j                  dj                  ||             % |j                  |        |S )a  Produce field paths from a message object.

  The result is used to create a FieldMask proto message that contains all field
  paths presented in the object.
  https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto

  Args:
    msg: A user defined message object that extends the messages.Message class.
    https://github.com/google/apitools/blob/master/apitools/base/protorpclite/messages.py

  Returns:
    The list of field paths.
  privatePoolV1Configprivate_pool_v1_confighybridPoolConfighybrid_pool_config
all_fieldsz{}.{})
rj   get_assigned_valuenamerepeatedr   ConvertToSnakeCasehasattrMessageToFieldPathsr>   format)ra   fieldsfieldvrl   fs         r   rp   rp     s     &~~euzz*A~~a}	,	,'::++# 33EJJ?	L	!$Q'A
--tQ/
0 ( 	d%  & 
-r   c                 N    t        j                  | |      }fd |       |S )aP  Stuff a dict into a proto message, and fail if there are unused values.

  Args:
    obj: dict(), The structured data to be reflected into the message type.
    msg_type: type, The proto message type.

  Raises:
    ValueError: If there is an unused value in obj.

  Returns:
    Proto message, The message that was created from obj.
  c                 6   t        | t        j                        r| j                         }|r?t	        |      dkD  rddj                  t        |            z  }n|d   }t        d|z        | j                         D ]!  }	 t        | |j                        } |       # t        | t              rt        |       D ]  \  }}	  |        yy# t        $ r}t        d|j                  |      d}~ww xY w# t        $ r}t        d||fz        d}~ww xY w)	z8Check for any unused fields in nested messages or lists.r   z{%s},r   z.%s: unused.Nz[%d]%s)r]   proto_messagesMessageall_unrecognized_fieldslenrT   r;   
ValueErrorrj   getattrrl   r`   	enumerate)	objunused_fields
unused_msg
used_fieldrs   eiitem_CheckForUnusedFieldss	           r   r   z1_UnpackCheckUnused.<locals>._CheckForUnusedFieldsC  s   #~--.113m	}! )> ??* %Q'*344(*	;#z/%

& ) #ts^'!T	.

% $   	;jooq9:
:	;  	.8q!f,-
-	.s0   CC:	C7C22C7:	DDD)r/   DictToMessage)r   msg_typera   r   s      @r   _UnpackCheckUnusedr   4  s+     	''X6#.6 	*r   c                    |g }	 t        j                  | |      }t        |t              st        j                  |d      t        |||||      S # t         j                  $ r%}t        j                  ||j
                        d}~ww xY w)a  Load a proto message from a stream of JSON or YAML text.

  Args:
    stream: file-like object containing the JSON or YAML data to be decoded.
    msg_type: The protobuf message type to create.
    msg_friendly_name: A readable name for the message type, for use in error
      messages.
    skip_camel_case: Contains proto field names or map keys whose values should
      not have camel case applied.
    path: str or None. Optional path to be used in error messages.

  Raises:
    ParserError: If there was a problem parsing the stream as a dict.
    ParseProtoException: If there was a problem interpreting the stream as the
    given message type.

  Returns:
    Proto message, The message that got decoded.
  N	file_hintz Could not parse as a dictionary.)	r   loadErrorr   ParserErrorinner_errorr]   r^   _YamlToMessage)streamr   msg_friendly_nameskip_camel_casepathstructured_datar   s          r   LoadMessageFromStreamr   c  s    0 OAii$7O 
OT	*

+
+D,NP P 
3D'
/ / 
 A

+
+D!--
@@As   A B
% BB
c           
          |g }	 t        j                  | |      }|D cg c]  }t        |||||       c}S # t         j                  $ r%}t        j                  ||j
                        d}~ww xY wc c}w )a  Load multiple proto message from a stream of JSON or YAML text.

  Args:
    stream: file-like object containing the JSON or YAML data to be decoded.
    msg_type: The protobuf message type to create.
    msg_friendly_name: A readable name for the message type, for use in error
      messages.
    skip_camel_case: Contains proto field names or map keys whose values should
      not have camel case applied.
    path: str or None. Optional path to be used in error messages.

  Raises:
    ParserError: If there was a problem parsing the stream.
    ParseProtoException: If there was a problem interpreting the stream as the
    given message type.

  Returns:
    Proto message list of the messages that got decoded.
  Nr   )r   load_allr   r   r   r   r   )r   r   r   r   r   r   r   r   s           r   LoadMessagesFromStreamr     s    0 OAmmFd;O "
!$ T8%6N!
  
 A

+
+D!--
@@A
s   : A5A2 A--A2c                     t        | |      } 	 t        | |      }|S # t        $ r}t        j                  ||d|z        d}~ww xY w)az  Load a proto message from a file containing JSON or YAML text.

  Args:
    structured_data: Dict containing the decoded YAML data.
    msg_type: The protobuf message type to create.
    msg_friendly_name: A readable name for the message type, for use in error
      messages.
    skip_camel_case: Contains proto field names or map keys whose values should
      not have camel case applied.
    path: str or None. Optional path to be used in error messages.

  Raises:
    ParseProtoException: If there was a problem interpreting the file as the
    given message type.

  Returns:
    Proto message, The message that got decoded.
  z%sN)r_   r   	Exceptionr   ParseProtoException)r   r   r   r   r   ra   r   s          r   r   r     s[    2 !/B/>
_h
7C 
* 
 >  
3
3D:K481H> >	>s    	A?Ac                 v    t        j                  |       5 }t        |||||       cddd       S # 1 sw Y   yxY w)a  Load a proto message from a file containing JSON or YAML text.

  Args:
    path: The path to a file containing the JSON or YAML data to be decoded.
    msg_type: The protobuf message type to create.
    msg_friendly_name: A readable name for the message type, for use in error
      messages.
    skip_camel_case: Contains proto field names or map keys whose values should
      not have camel case applied.

  Raises:
    files.MissingFileError: If the file does not exist.
    ParserError: If there was a problem parsing the file as a dict.
    ParseProtoException: If there was a problem interpreting the file as the
    given message type.

  Returns:
    Proto message, The message that got decoded.
  N)r   
FileReaderr   r   r   r   r   ru   s        r   LoadMessageFromPathr     s4    .  H.?!0$8    /8c                 v    t        j                  |       5 }t        |||||       cddd       S # 1 sw Y   yxY w)a  Load a proto message from a file containing JSON or YAML text.

  Args:
    path: The path to a file containing the JSON or YAML data to be decoded.
    msg_type: The protobuf message type to create.
    msg_friendly_name: A readable name for the message type, for use in error
      messages.
    skip_camel_case: Contains proto field names or map keys whose values should
      not have camel case applied.

  Raises:
    files.MissingFileError: If the file does not exist.
    ParseProtoException: If there was a problem interpreting the file as the
    given message type.

  Returns:
    Proto message list of the messages that got decoded.
  N)r   r   r   r   s        r   LoadMessagesFromPathr     s4    , !!X/@"149 r   c                 H    t        t        j                  t        |             S )zDetermine if the provided full resource name is a worker pool.

  Args:
    resource_name: str, The string to test.

  Returns:
    bool, True if the string is a worker pool's full resource name.
  )boolrematchWORKERPOOL_NAME_MATCHER)resource_names    r   IsWorkerPoolr     s     
bhh.>	??r   c                     t        j                  t        |       }|r|j                  d      S t	        dt
        d      )aB  Get the name part of a worker pool's full resource name.

  For example, "projects/abc/locations/def/workerPools/ghi" returns "ghi".

  Args:
    resource_name: A worker pool's full resource name.

  Raises:
    ValueError: If the full resource name was not well-formatted.

  Returns:
    The worker pool's short name.
  r   *The worker pool resource name must match "")r   searchWORKERPOOL_NAME_SELECTORgroupr~   r   r   r   s     r   WorkerPoolShortNamer     s;     )),m
<%
;;q>+. 	/ /r   c                     t        j                  t        |       }|r|j                  d      S t	        dt
        d      )aQ  Get the region part of a worker pool's full resource name.

  For example, "projects/abc/locations/def/workerPools/ghi" returns "def".

  Args:
    resource_name: str, A worker pool's full resource name.

  Raises:
    ValueError: If the full resource name was not well-formatted.

  Returns:
    str, The worker pool's region string.
  r   r   r   )r   r   WORKERPOOL_REGION_SELECTORr   r~   r   r   s     r   WorkerPoolRegionr   0  s;     )).
>%
;;q>+. 	/ /r   c                 t   t               }|j                         }| j                  |_        | j                  |_        | j                  | j                  |_        |s| j                  | j                  |_	        | j                  X|j                         }| j                  |_        | j                  |_        | j                  | j                  |_        ||_        |S |j#                         }| j$                  |_        | j(                  |_        | j,                  |_        | j0                  |_        ||_        |S )a.  Construct the GitHubEnterpriseConfig resource from the command line args.

  Args:
    args: An argparse namespace. All the arguments that were provided to this
        command invocation.
      update: bool, if the args are for an update.

  Returns:
    A populated GitHubEnterpriseConfig message.
  )r!   GitHubEnterpriseConfighost_urihostUrlapp_idappIdwebhook_key
webhookKeypeered_networkpeeredNetwork
gcs_bucketGCSLocationbucket
gcs_objectobject
generationappConfigJsonGitHubEnterpriseSecretsprivate_key_nameprivateKeyNamewebhook_secret_namewebhookSecretNameoauth_secret_nameoauthSecretNameoauth_client_id_nameoauthClientIdNamesecrets)argsupdater   ghegcs_locationsecret_locations         r   GitHubEnterpriseConfigFromArgsr   E  s     ('')##+kk#)	!%%CN	D''3++C	__ '')L//L//L" $l$C 
* 668O%)%:%:O"(,(@(@O%&*&<&<O#(,(A(AO%!CK	*r   c                 <   t               }|j                         }| j                  |_        | j                  |_        | j                  |_        |j                         }| j                  |_
        | j                  |_        | j                  |_        |s|||_        |s\| j                   "| j"                  t%        j&                  dd      | j                   "| j                   |_        | j"                  |_        | j-                  d      r| j.                  |_        |S )a"  Construct the BitbucketServer resource from the command line args.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.
    update: bool, if the args are for an update.

  Returns:
    A populated BitbucketServerConfig message.
  zpeered-network-ip-rangezG--peered-network is required when specifying --peered-network-ip-range.ssl_ca_file)r!   BitbucketServerConfigr   hostUri	user_nameusernameapi_keyapiKeyBitbucketServerSecrets!admin_access_token_secret_versionadminAccessTokenVersionName read_access_token_secret_versionreadAccessTokenVersionNamewebhook_secret_secret_versionwebhookSecretVersionNamer   r   peered_network_ip_rangec_exceptionsRequiredArgumentExceptionr   peeredNetworkIpRangeIsSpecifiedr   sslCa)r   r   r   bbsr   s        r   BitbucketServerConfigFromArgsr   j  s     (&&(##+#,||#*335/
,, - ++ , .2-O-O/**!CK	"t'C'C'O22
#,  &--c!%!=!=c	m$  CI	*r   c                 "   t               }|j                         }| j                  |_        |j	                         }| j
                  |_        | j                  |_        | j                  |_
        | j                  |_        t        |      s||_        |j                         }| j                   |_        |j%                         }| j&                  |_        ||_        | j-                  d      r| j.                  |_        t        |      s||_        |S )zConstruct the GitLabConfig resource from the command line args.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      command invocation.

  Returns:
    A populated GitLabConfig message.
  r   )r!   GitLabConfigr   r   GitLabSecretsapi_access_token_secret_versionapiAccessTokenVersionr   readAccessTokenVersionr   webhookSecretVersionapi_key_secret_versionapiKeyVersion_IsEmptyMessager   GitLabEnterpriseConfigr   r   ServiceDirectoryConfigservice_directory_serviceserviceserviceDirectoryConfigr   r   r   enterpriseConfig)r   r   configr   enterprise_configservice_directory_configs         r   GitLabConfigFromArgsr    s      (  "&NN&/""$'"&"F"F'#'#H#H' !%!C!C'55'		!FN557"mm%<<>%)%C%C"-E*	m$"..	*	+/F	-r   c                 f    | yt        j                  |       }t        |j                                S )NT)r/   MessageToDictanyvalues)messagemessage_dicts     r   r   r     s1    _"009,$$&'	''r   c                     | d uxrL | j                   d uxr< | j                   j                  d uxr" | j                   j                  j                  d uS N)optionspoolrl   build_configs    r   WorkerPoolIsSpecifiedr    s\    $ 5


d
*5



#
#4
/5 


#
#
(
(
4	r   c                     | d uxrL | j                   d uxr< | j                   j                  d uxr" | j                   j                  j                  d uS r  )r  r  workerConfigr  s    r   WorkerPoolConfigIsSpecifiedr    s\    $ =


d
*=



#
#4
/= 


#
#
0
0
<	r   c                     | sy| t         z  S )zConverts bytes to GB.

  Args:
    size: a size in GB  Does not require size to be a multiple of 1 GB unlike
      utils.BytesToGb from from googlecloudsdk.api_lib.compute

  Returns:
    size in bytes.
  N)BYTES_IN_ONE_GB)sizes    r   	BytesToGbr    s     
		  r   r  )NN)F)F__doc__
__future__r   r   r   enumr   apitools.base.protorpcliter   rz   apitools.base.pyr   r/   !googlecloudsdk.api_lib.cloudbuildr   googlecloudsdk.api_lib.utilr	   googlecloudsdk.callioper
   r   r   googlecloudsdk.corer   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r<   r"   _GA_API_VERSION_BETA_API_VERSIONReleaseTrackGABETAALPHAr#   r   r   r   DEFAULT_REGIONr  Enumr   r!   r'   r+   r4   rB   rJ   rM   rO   r[   r_   rp   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r   r   r   <module>r,     s   ( &  '  	 A : C , ( > $ : * 
	  	/O_   E G I  dii  %)$5$5$8$8 M "&!2!2!5!5 J ##&& 4IB FBBB6"J,d +/#	$/T ,0 $	#R $(	%V )-8> *.96	@/*/*"J)X!H(!r   