
    R                     D   S r SSKJr  SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSK	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$  SSK"J%r%  SSK"J&r&  SSK'J(r(  SSK)J*r*  SSK+r,Sr-\	R\                  " S5      r/Sr0\	R\                  " S5      r1Sr2\	R\                  " S5      r3Sr4Sr5SS /r6/ S!Qr7\*Rp                  Rr                  Rt                  r;\Rx                  Rz                  4S" jr>\Rx                  Rz                  4S# jr?S$ r@\Rx                  Rz                  4S% jrAS& rBS'rCS(rDS)\C-   S*-   rES+\C-   S,-   \D-   S--   rFS.\F-   S,-   \E-   S/-   rGS0\F-   S,-   \E-   S1-   \G-   S2-   rHS3rIS4 rJS5 rKS6 rLS7 rMS8 rNS9 rOS: rPS; rQS< rRS= rS\SS> 5       rT\SS? 5       rU\S SLS@ j5       rV\SSA 5       rW\SSB 5       rX\SSC 5       rY\S  SMSD j5       rZ\S  SMSE j5       r[\SSF 5       r\SG r]SH r^SI r_SJ r`SK rag)Nz5A library that is used to support Functions commands.    )absolute_import)division)print_function)unicode_literalsN)base_api)
exceptions)
list_pager)
operations)util)storage_api)storage_util)apis)arg_parsers)base)iam_util)log)
properties)	resources)encoding)cloudfunctions_v1_messagesz7Deploying function (may take a while - up to 2 minutes)z3^(.*/)?[A-Za-z](?:[-_A-Za-z0-9]{0,61}[A-Za-z0-9])?$zFunction name must contain only Latin letters, digits and a hyphen (-). It must start with letter, must not end with a hyphen, and must be at most 63 characters long.z%^[a-zA-Z][\-\._~%\+a-zA-Z0-9]{2,254}$zTopic must contain only Latin letters (lower- or upper-case), digits and the characters - + . _ ~ %. It must start with a letter and be from 3 to 255 characters long.z^projects/_/buckets/.{3,222}$cloudfunctionsv1z
asia-east1zeurope-west6)zsouthamerica-east1zus-central1zus-east1zus-east4zus-west1c                     [         $ )ai  Returns the current cloudfunctions Api Version configured in the sdk.

NOTE: Currently the value is hard-coded to v1, and surface/functions/deploy.py
assumes this to parse OperationMetadataV1 from the response.
Please change the parsing if more versions should be supported.

Args:
  track: The gcloud track.

Returns:
  The current cloudfunctions Api Version.
)_API_VERSIONtracks    /lib/googlecloudsdk/api_lib/functions/v1/util.py_GetApiVersionr   W   s
     
    c                    [         R                  " 5       nU(       a  SU;  a$  [        R                  " [        [        U 5      5      $ [        R                  " S5        [        R                  R                  R                  S5      R                  S5        [        R                  " [        [        U 5      5      n[        R                  R                  R                  S5      R                  S5        U$ )z"Returns the GCFv1 client instance.zautopush-cloudfunctionszTemporarily overriding cloudfunctions endpoint to staging-cloudfunctions.sandbox.googleapis.com so that GCFv1 autopush resources can be accessed.r   z6https://staging-cloudfunctions.sandbox.googleapis.com/z7https://autopush-cloudfunctions.sandbox.googleapis.com/)v2_utilGetApiEndpointOverrider   GetClientInstance	_API_NAMEr   r   infor   VALUESapi_endpoint_overridesPropertySet)r   endpoint_overrideclients      r   GetApiClientInstancer,   g   s     446 	"*;	;!!)^E-BCC (($
 **334DEII> !!)^E-BC&**334DEII? 
-r   c                  0    [         R                  " SS5      $ )Ncloudresourcemanagerr   )r   r#    r   r   #GetResourceManagerApiClientInstancer0      s    			 6	==r   c                 J    [         R                  " [        [        U 5      5      $ N)r   GetMessagesModuler$   r   r   s    r   GetApiMessagesModuler4      s    				>%+@	AAr   c                    [         R                  R                  U [        R                  R
                  R                  R                  SS9[        R                  R                  R                  R                  5       S.SS9$ )NTrequired)
projectsIdlocationsIdz+cloudfunctions.projects.locations.functions)params
collection)
r   REGISTRYParser   r&   coreprojectGet	functionsregionnames    r   GetFunctionRefrE      sn    				!	!
"))..66::D:I#**44;;??A ? 
" 
 r   z[a-zA-Z0-9_]z[][~@#$%&.,?:;+*='()-]z(\{z(=\*\*?)?})z((|z)+)z(/(z))z(/?()z*)zgPath must be a slash-separated list of segments and captures. For example, [users/{userId}/profilePic].c                    U R                   R                  nU R                   R                  nSn [        R                  " U R
                  5      nSU;   aJ  US   nSU;   a  US   n[        U 5      nU(       a  USU-   -  nUS:X  a  [        U5      nU(       a  USU-   -  nSR                  X[        R                  " U5      5      $ ! [        [        4 a    U R
                  n NDf = f)zReturns a human readable string representation from the http response.

Args:
  error: HttpException representing the error response.

Returns:
  A human readable string representation of the error.
 errormessagez
Problems:
i  z
Permission Details:
z6ResponseError: status=[{0}], code=[{1}], message=[{2}])responsestatusreasonjsonloadscontent_GetViolationsFromError_GetPermissionErrorDetails
ValueError	TypeErrorformatr   Decode)rJ   rM   coderK   data
error_info
violationspermission_issuess           r   GetHttpErrorMessager]      s     >>  &			$'::emm$D$=j	j	 Y'*51j	?Z//	36zB
.1BB
B' 
B	H	HHOOG,
  i	  mmGs   A0C C%$C%c                     [        U[        5      (       a  [        R                  " X5      nOUR                  U 5      nU(       d%  [        R
                  " SR                  X5      5      eU $ )NzInvalid value '{0}': {1})
isinstancestrrematchr   ArgumentTypeErrorrV   )argumentregexerror_messagerb   s       r   _ValidateArgumentByRegexOrRaiserg      sV    sHHU%EKK!E	

'
'"))(B  
/r   c                 ,    [        U [        [        5      $ )zChecks if a function name provided by user is valid.

Args:
  name: Function name provided by user.

Returns:
  Function name.
Raises:
  ArgumentTypeError: If the name provided by user is not valid.
)rg   _FUNCTION_NAME_RE_FUNCTION_NAME_ERRORrC   s    r   ValidateFunctionNameOrRaiserk      s     
)
3
 r   c                 ~   [         R                  U 5      (       a   [        R                  R	                  U 5      nO [        R                  R                  U SS9nUR                  5       R                  S5      S-   n U $ ! [        R                   a*  n[        R                  " SR                  X5      5      eSnAff = f)a  Checks if a bucket uri provided by user is valid.

If the Bucket uri is valid, converts it to a standard form.

Args:
  bucket: Bucket uri provided by user.

Returns:
  Sanitized bucket uri.
Raises:
  ArgumentTypeError: If the name provided by user is not valid.
F)require_prefixzInvalid value '{}': {}N/)_BUCKET_RESOURCE_URI_RErb   r   BucketReferenceFromUrlFromArgumentargparserc   r   rV   ToUrlrstrip)bucket
bucket_refes      r   %ValidateAndStandarizeBucketUriOrRaisery      s     ""6**--55f=J//<<
 = j $$S)C/&	- %% ))
"
)
)&
4 s   A> >B<%B77B<c                 0    [        U [        [        5      n U $ )zChecks if a Pub/Sub topic name provided by user is valid.

Args:
  topic: Pub/Sub topic name provided by user.

Returns:
  Topic name.
Raises:
  ArgumentTypeError: If the name provided by user is not valid.
)rg   _TOPIC_NAME_RE_TOPIC_NAME_ERROR)topics    r   ValidatePubsubTopicNameOrRaiser~   
  s     *^.% 
,r   c                    U R                  USR                  XR                  R                  R                  R
                  5      S9nU(       a  UR                  c  g[        UR                  5      S:  a%  [        R                  " SR                  U5      5      eUR                  S   nU(       a   UR                  (       a  UR                  S   $ S$ )a  Checks if runtime is supported.

Does not raise if the runtime list cannot be retrieved

Args:
  client: v2 GCF client that supports ListRuntimes()
  runtime: str, the runtime.
  region: str, region code.

Returns:
  warning: None|str, the warning if deprecated
zname={} AND environment={})query_filterN   zargument `--runtime`: {} is not a supported runtime on GCF 1st gen. Use `gcloud functions runtimes list` to get a list of available runtimesr   )ListRuntimesrV   messagesRuntimeEnvironmentValueValuesEnumGEN_1runtimeslenr   FunctionsErrorwarnings)r+   runtimerB   rL   runtime_infos        r   ValidateRuntimeOrRaiser     s       /66
??**EEKK ! ( 
X&&.		a

#
#	!!' 
 ""1%, 
,// A r   c                 0    [        U [        [        5      n U $ )zCheck if path provided by user is valid.

Args:
  path: A string: resource path

Returns:
  The argument provided, if found valid.
Raises:
  ArgumentTypeError: If the user provided a path which is not valid
)rg   _PATH_PATH_RE_ERROR)paths    r   ValidatePathOrRaiser   A  s     
)un	E$	+r   c           
         [         R                  " U 5      n/ nUR                  UR                  R	                  5        VVs/ s H  u  p4SR                  X45      PM     snn5        UR                  UR                  R	                  5        VVs/ s H  u  p4SR                  X45      PM     snn5        U(       a  SR                  U5      S-   $ gs  snnf s  snnf )zLooks for violations descriptions in error message.

Args:
  error: HttpError containing error information.

Returns:
  String of newline-separated violations descriptions.
z{}:
{}
rI   )exceptions_utilHttpErrorPayloadextendr[   itemsrV   field_violationsjoin)rJ   error_payloaderrorskvs        r   rR   rR   P  s     "2259-&--*7*B*B*H*H*JK*J$!y*JK 	-- $44::<<da 

1
 < 99Vt##	 Ls   C
C
c                 d     SU ;   a  U S   S   nSU;   a  US   $ g! [         [        4 a     gf = f)zLooks for permission denied details in error message.

Args:
  error_info: json containing error information.

Returns:
  string containing details on permission issue and suggestions to correct.
detailsr   detailN)rT   rU   )rZ   r   s     r   rS   rS   i  sR    	J9%a(g	W	x   
 i	  			s    //c                 F   ^  [         R                  " T 5      U 4S j5       nU$ )zDDecorator that catches HttpError and raises corresponding exception.c                     >  T" U 0 UD6$ ! [         R                   a=  n[        R                  " [        R
                  " [        U5      5      5         S nAg S nAff = fr2   )apitools_exceptions	HttpErrorcore_exceptionsreraisebase_exceptionsHttpExceptionr]   )argskwargsrJ   funcs      r   "CatchHTTPErrorRaiseHTTPExceptionFnLCatchHTTPErrorRaiseHTTPException.<locals>.CatchHTTPErrorRaiseHTTPExceptionFn  sU    4"6""(( 

'
'(;E(B
C s    A3AA)	functoolswraps)r   r   s   ` r    CatchHTTPErrorRaiseHTTPExceptionr   }  s(     ??4  
,+r   c                 (   [        5       nUR                  n UR                  R                  UR	                  U S95      $ ! [
        R                   a=  nUR                  [        R                  R                  R                  :X  a   SnAge SnAff = f)zFReturns the Get method on function response, None if it doesn't exist.rC   N)r,   MESSAGES_MODULEprojects_locations_functionsr@   2CloudfunctionsProjectsLocationsFunctionsGetRequestr   r   status_codesixmoveshttp_client	NOT_FOUND)function_namer+   r   rJ   s       r   GetFunctionr     s      !&##(
..22CC 	D 	
 
 
	&	& 
CII11;;;		
s   'A   B2BBBc            
         [        5       n U R                  n[        R                  " U R                  UR                  S[        R                  R                  R                  R                  SS9-   S9SSS9n[        R                  " 5       [        R                  R                  L a>  [        R                   " S5        U Vs/ s H  o3R"                  [$        ;   d  M  UPM     sn$ [        R                  " 5       [        R                  R&                  L a>  [        R                   " S	5        U Vs/ s H  o3R"                  [(        ;   d  M  UPM     sn$ U$ s  snf s  snf )
z;Returns the list of regions where GCF 1st Gen is supported.z	projects/Tr6   rC   	locationspageSize)servicerequestfieldbatch_size_attributezFListRegions: Autopush env detected. Filtering for v1 autopush regions.zDListRegions: Staging env detected. Filtering for v1 staging regions.)r,   r   r	   YieldFromListprojects_locations*CloudfunctionsProjectsLocationsListRequestr   r&   r>   r?   r@   r!   GetCloudFunctionsApiEnvApiEnvAUTOPUSHr   r%   
locationId_V1_AUTOPUSH_REGIONSSTAGING_V1_STAGING_REGIONS)r+   r   resultsrs       r   ListRegionsr     s     !&##($$''AAZ..33;;???NN B  %' $$&'..*A*AAHHP Gw!,,2F"FAwGG&&(GNN,B,BBHHN Fw!,,2E"EAwFFN H
 Gs   EE/E
Ec           	      f    [        5       n[        R                  " U UR                  U[        UUS9  g)a  Wait for the specied function update to complete.

Args:
  op: Cloud operation to wait on.
  try_set_invoker: function to try setting invoker, see above TODO.
  on_every_poll: list of functions to execute every time we poll. Functions
    should take in Operation as an argument.
)try_set_invokeron_every_pollN)r,   r
   Waitr   _DEPLOY_WAIT_NOTICE)opr   r   r+   s       r   WaitForFunctionUpdateOperationr     s0      !&//%!r   c                     [        5       nUR                  nSR                  [        U5      5      nUR                  R                  UR                  U U R                  US95      $ )zCall the api to patch a function based on updated fields.

Args:
  function: the function to patch
  fields_to_patch: the fields to patch on the function

Returns:
  The cloud operation for the Patch.
,)cloudFunctionrD   
updateMask)r,   r   r   sortedr   Patch4CloudfunctionsProjectsLocationsFunctionsPatchRequestrD   )functionfields_to_patchr+   r   fields_to_patch_strs        r   PatchFunctionr     se      !&##(!89		,	,	2	2CC }}( D 
 r   c                 ~    [        5       nUR                  nUR                  R                  UR	                  XS95      $ )zCall the api to create a function.

Args:
  function: the function to create
  location: location for function

Returns:
  Cloud operation for the create.
)locationr   )r,   r   r   Create5CloudfunctionsProjectsLocationsFunctionsCreateRequest)r   r   r+   r   s       r   CreateFunctionr     sG      !&##(		,	,	3	3DD E 
 r   c                 ~    [        5       nUR                  nUR                  R                  UR	                  U S95      $ )N)resource)r,   r   r   GetIamPolicy;CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest)function_resource_namer+   r   s      r   GetFunctionIamPolicyr      sE    !&##(		,	,	9	9JJ) K 
 r   c           	          [        5       nUR                  n[        U 5      n[        R                  " UR
                  XQU5        UR                  R                  UR                  U UR                  US9S95      $ )Npolicyr   setIamPolicyRequest)
r,   r   r   r   AddBindingToIamPolicyBindingr   SetIamPolicy;CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequestSetIamPolicyRequestr   memberroler+   r   r   s         r   AddFunctionIamPolicyBindingr     s{      !&##( 67&
  !1!164H		,	,	9	9JJ)&::&:I K 
 r   c           	         [        5       nUR                  n[        U 5      n[        R                  " XQU5      (       d  U$ [        R
                  " XQU5        UR                  R                  UR                  U UR                  US9S95      $ )z4Removes the specified policy binding if it is found.r   r   )
r,   r   r   r   BindingInPolicyRemoveBindingFromIamPolicyr   r   r   r   r   s         r   %RemoveFunctionIamPolicyBindingIfFoundr     s      !&##( 67&		!	!&$	7	7M
%%fd;		,	,	9	9JJ)&::&:I K 
 r   c                     [        5       nUR                  nSS/nUR                  U UR                  US9S9nUR                  R                  U5      nSnU H  nXuR                  ;  d  M  SnM     U$ )z@Returns True iff the caller can add policy bindings for project.z%resourcemanager.projects.getIamPolicyz%resourcemanager.projects.setIamPolicy)permissions)r   testIamPermissionsRequestTF)r0   r   5CloudresourcemanagerProjectsTestIamPermissionsRequestTestIamPermissionsRequestprojectsTestIamPermissionsr  )r?   r+   r   needed_permissionsiam_requestiam_responsecan_addneeded_permissions           r   CanAddFunctionIamPolicyBindingr  2  s     /0&##(-- NN ( B B( !C ! O + 33K@,'- 8 88g . 
.r   c                    [        5         [        X5      n [        R                  " 5       R	                  [
        R                  R                  U5      5      nU(       a5  [        R                  " USS5      (       a  [        R                  " S5        ggg! [        R                   a    [        R                  " S5         gf = f)zValidates image repository. Yields security and deprecation warnings.

Args:
  region_name: String name of the region to which the function is deployed.
  project_id: String ID of the Cloud project.
allUserszroles/storage.objectViewera  The Container Registry repository that stores this function's image is public. This could pose the risk of disclosing sensitive data. To mitigate this, either use Artifact Registry ('--docker-registry=artifact-registry' flag) or change this setting in Google Container Registry.
a  Secuirty check for Container Registry repository that stores this function's image has not succeeded. To mitigate risks of disclosing sensitive data, it is recommended to keep your repositories private. This setting can be verified in Google Container Registry.
N)_AddGcrDeprecationWarning GetStorageBucketForGcrRepositorygcs_apiStorageClientr   r   rp   rq   r   r   r   warningr   r   )region_name
project_idgcr_bucket_urlgcr_host_policys       r   #ValidateSecureImageRepositoryOrWarnr  I  s     3KL.++-::$$,,^<O 833%A  
kk4 
	&	& KK	Ps   A;B *CCc                 4    SR                  [        U 5      US9$ )a   Retrieves the GCS bucket that backs the GCR repository in specified region.

Args:
  region_name: String name of the region to which the function is deployed.
  project_id: String ID of the Cloud project.

Returns:
  String representing the URL of the GCS bucket that backs the GCR repo.
z5gs://{multiregion}.artifacts.{project_id}.appspot.com)multiregionr  )rV   _GetGcrMultiregion)r  r  s     r   r  r  i  s)     
A	G	G$[1 
H 
 r   c                     U R                  S5      (       a  gU R                  S5      (       d  U R                  S5      (       a  gg)z@Returns String name of the GCR multiregion for the given region.europeeuasia	australiaus)
startswith)r  s    r   r  r  y  s?     H%%f%%)?)?)L)Lr   c                 (    U R                   [        :H  $ r2   )dockerRegistry_DOCKER_REGISTRY_GCR)r   s    r   IsGcrRepositoryr&    s    		 	 $8	88r   c                  0    [         R                  " S5        g)z2Adds warning on deprecation of Container Registry.a  Due to the general transition from Container Registry to Artifact Registry, `--docker-registry=container-registry` will no longer be available as an option when deploying a function. All container image storage and management will automatically transition to Artifact Registry. For more information, please visit: https://cloud.google.com/artifact-registry/docs/transition/transition-from-gcrN)r   r  r/   r   r   r  r    s    ++Xr   )NN)r  zroles/cloudfunctions.invoker)b__doc__
__future__r   r   r   r   rs   r   rO   ra   apitools.base.pyr   r   r   r	   #googlecloudsdk.api_lib.functions.v1r
   #googlecloudsdk.api_lib.functions.v2r   r!   googlecloudsdk.api_lib.storager   r  r   googlecloudsdk.api_lib.utilr   r   googlecloudsdk.callioper   r   calliope_baser   googlecloudsdk.command_lib.iamr   googlecloudsdk.corer   r   r   r   googlecloudsdk.core.utilr   7googlecloudsdk.generated_clients.apis.cloudfunctions.v1r   six.moves.http_clientr   r   compileri   rj   r{   r|   ro   r$   r   r   r   CloudFunctionDockerRegistryValueValuesEnumCONTAINER_REGISTRYr%  ReleaseTrackGAr   r,   r0   r4   rE   _ID_CHAR_P_CHAR_CAPTURE_SEGMENT_PARTr   r   r]   rg   rk   ry   r~   r   r   rR   rS   r   r   r   r   r   r   r   r   r   r  r  r  r  r&  r  r/   r   r   <module>rA     s    < &  % '    	 % > ' : : ? A 7 , E / 9 A 3 = # * ) - ^ O JJ: .  DE  **%EF 	$n5   ,,JJ]] 
 '3366    -99<< B>  -99<< B 
"
 H~-(?S 7*U23)D0C(*S0584?: B	 <"#L2(, "
 "
$ " "< ",0 ", " ", " "& " " " 	' "" " 	' "( " ",@ 9
r   