
    ?                         S r SSKJr  SSKJr  SSKJ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 rS rS rS rS rS rS rS rS rg)zACommands for Developer Connect Insights Config Deployment Events.    )absolute_import)division)unicode_literalsN)encoding)
exceptions)vulnerabilities)requests)apis)	resourcesc                    UR                   nU (       d  0 $ U n[        R                  " U5      n[        US5      (       a  UR                  (       a  SU;   a  US    H  nUR                  S5      nU(       d  M  [        X&5      =(       d    / US'   / n SU-   n[        R                  " X(S5      n	[        U	5      n
U
 HX  nUR                  (       d  M  UR                  R                  (       d  M3  UR                  UR                  R                  5        MZ     XuS'   M     U$ ! [        R                  [        R                   4 a"  n[#        SU SU 35        / US'    SnAGM  SnAff = f)	a/  A hook function to modify the response of a deployment-event describe.

This function enriches the deployment event with vulnerability and package
dependency details by calling the Container Analysis API for each
artifactDeployment. The response is converted to a dictionary to allow adding
custom fields.

Args:
  response: The original response from the API, expected to be a
    DeploymentEvent object.
  args: Command line arguments, contains the project.

Returns:
  A dictionary representing the deployment event with added vulnerability
  information.
artifactDeploymentsartifactReferencepackageshttps://Nr   #Error fetching vulnerabilities for : )projectr   MessageToPyValuehasattrr   get!_FetchAndParsePackageDependenciesr   GetVulnerabilitieslistvulnerabilityshortDescriptionappendapitools_exceptions	HttpErrorr   Errorprint)responseargsr   event
event_dictartifact_dictartifact_ref	cve_namesresource_urioccurrencesoccurrences_listocces                ]lib/googlecloudsdk/command_lib/developer_connect/insights_configs/deploymentevent_describe.pyAddArtifactDetailsToResponser.       s]   $ LL'	I
%((/* U)**u/H/H
*%&;<-$(()<=
 .gDJ 	j! 		0#l2,'::T+ "+.
%c   S%6%6%G%G%Gs00AAB & .7)
*3 => 
 $--z/?/?@ 	0
5l^2aSI
J-/-)
*
*	0s$   ;D!D!.-D!!$E'E""E'c                     [         R                  " SU 5      nU(       a"  UR                  S5      UR                  S5      4$ g)zParses a source commit URI to extract the base repo URL and commit SHA.

Args:
  uri: The source commit URI string (e.g.,
    https://github.com/owner/repo/commit/sha).

Returns:
  A tuple (base_repo_url, commit_sha) or (None, None) if parsing fails.
zZ(https?://(?:github\.com|gitlab\.com|bitbucket\.org)/[^/]+/[^/]+)/commit/([0-9a-fA-F]{40})      )NN)rematchgroup)urir3   s     r-   _ParseSourceCommitUrir6   _   s;     ((c	% ;;q>5;;q>))	    c                 d    SU ;   a
  U  SU SU 3$ SU ;   a
  U  SU SU 3$ SU ;   a
  U  SU SU 3$ g)	aY  Constructs a Git-diff URI for GitHub, GitLab, or Bitbucket.

Args:
  base_repo_url: The base URL of the repository (e.g.,
    https://github.com/owner/repo).
  prev_sha: The commit SHA of the previous deployment.
  curr_sha: The commit SHA of the current deployment.

Returns:
  The Git-diff URI string or None if the provider is not supported.
z
github.comz	/compare/z...z
gitlab.comz/-/compare/zbitbucket.orgz..N )base_repo_urlprev_shacurr_shas      r-   _ConstructGitDiffUrir=   u   sd     ]"_IhZs8*==}$_KzXJ??-'_IhZr(<<	r7   c                     U (       d  gSnSnU  HE  nUR                  S5      nUR                  S5      nU(       d  M.  U(       d  M7  Ub  XB:  d  MA  UnUnMG     U(       a  UR                  S5      S   $ g)zSGets the source commit URI from the artifact deployment with the latest deployTime.N
deployTimesourceCommitUrisr   r   )artifact_deployments	latest_adlatest_deploy_timeaddeploy_time_strsource_uriss         r-   _GetLatestSourceCommitUrirH      sv    	) bff\*O&&+,K;;		#'K,	 ! ==+,Q//	r7   c                    / n SU-   nSU S3n[         R                  " X5      n[        U5      nU Hi  nUR                  (       d  M  UR                  nUR                  UR
                  (       a  UR
                  R                  OSS.n	UR                  U	5        Mk     U$ ! [        R                  [        R                  4 a  n
[        SU SU
 35        / s Sn
A
$ Sn
A
ff = f)z?Fetches and parses PACKAGE occurrences from Container Analysis.r   z!kind="PACKAGE" AND resource_url=""N)nameversionz(Error fetching package dependencies for r   )ca_requestsListOccurrencesr   packagerK   rL   fullNamer   r   r   r   r   r    )r   r&   package_depsr(   
res_filterr)   r*   r+   pkgdetailr,   s              r-   r   r      s    , ,L4\N!DJ--gBKK(	kkHH/2{{s{{++
 	F#   
	 
'
')9)9	: 	4\N"QC
HIIs%   A B! AB! !$C"CC"C"c                 6   0 nU  HV  nUR                  S/ 5       H=  nUR                  S5      (       d  M  UR                  S5      (       d  M3  US   X$S   '   M?     MX     0 nU HV  nUR                  S/ 5       H=  nUR                  S5      (       d  M  UR                  S5      (       d  M3  US   XTS   '   M?     MX     / n/ n0 nUR                  5        H7  u  pX;  a  UR                  U	 SU
 35        M"  XY   U
:w  d  M,  XY    SU
 3X'   M9     UR                  5        H"  u  pX;  d  M  UR                  U	 SU 35        M$     0 nU(       a  SR                  [	        U5      5      US'   U(       a  SR                  [	        U5      5      US'   U(       a  XS	'   U$ )
z6Computes overall added, removed, and changed packages.r   rK   rL   z==z -> , addedPackagesremovedPackageschangedVersions)r   itemsr   joinsorted)
current_adprevious_adcurr_maprE   pprev_map
added_pkgsremoved_pkgschanged_verspkg_namecurr_verprev_verdiffs                r-   _ComputeOverallPackageDiffri      s   (bVVJ#	
v155++	l6 $ 
 (bVVJ#	
v155++	l6 $ 
 *,, %NN,h8*Bxj12		x	'"*"4!5T(Dl	 - %NN,hXJb
34 - 
$ IIfZ&89D"ii|(<=D	*		+r7   c                    U (       d  gU  H  nUR                  S5      nU(       a  SU;   a  M#  / n SU-   n[        R                  " XS5      nU HX  nUR                  (       d  M  UR                  R                  (       d  M3  UR                  UR                  R                  5        MZ     XBS'   M     g! [        R                  [        R                  4 a!  n[        SU SU 35        / US'    SnAM  SnAff = f)zIFetches and populates vulnerabilities for a list of artifact deployments.Nr   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r    )	artifact_dictsr   r%   r&   r'   r(   r)   r+   r,   s	            r-   _PopulateVulnerabilitiesrl      s    	
%m $$%89L,=I,,.l#66
k #!2!2!C!C!C


3,,==
>  *3%& &  )):+;+;< ,1,r!EF)+m%&,s#   0B4%B4-B44$C9C44C9c                     [        [        X-
  5      5      n[        [        X-
  5      5      n0 nU(       a  SR                  U5      US'   U(       a  SR                  U5      US'   U$ )z3Computes overall added and removed vulnerabilities.rV   addedVulnerabilitiesremovedVulnerabilities)r\   r   r[   )all_curr_vulnsall_prev_vulnsnew_vulnerabilitiesremoved_vulnerabilitiesrh   s        r-    _ComputeOverallVulnerabilityDiffrt      sb    tN$CDE"4(G#HI	$#'99-@#AD	 %)YY/F%GD	!"	+r7   c                 	   UR                   (       d  U $ U nUR                  n0 / 0 0 S.0 S.S.US'   UR                  S5      nU(       d  U$  [        R                  R                  USS9nUR                  5       R                  5       nSnUR                  S5      n	U	(       a  U	R                  S5      (       a  U	S   nOU$ [        R                  " SS5      n
[        R                  " SS5      nUR                  USU S3SS9n U
R                  R                  U5      nUR                   =(       d    /  Vs/ s H  n["        R$                  " U5      PM     nnU(       d  U$ S n[)        XSS9nSn[+        U5       H  u  nnUR                  S5      U:X  d  M  Un  O   US:X  a  U$ SnUS-   [-        U5      :  a&  UUS-      n[        SUR                  S5       35        OU$ [/        UR                  S/ 5      5      n[/        UR                  S/ 5      5      nU(       a  U(       ay  [1        U5      u  nn[1        U5      u  nnU(       aJ  U(       aC  U(       a<  U(       a5  UU:X  a/  UU:w  a)  [3        UUU5      nU(       a	  UUS   S'   O#[        S5        O[        S5        O[        S5        UR                  S/ 5      nUR                  S/ 5      nU H=  nUR                  S5      nU(       d  M  S U;  d  M%  [5        UU5      =(       d    / US '   M?     U H=  nUR                  S5      nU(       d  M  S U;  d  M%  [5        UU5      =(       d    / US '   M?     [7        UU5      n U US   S!   S"'   [9        UU5        [9        UU5        [;        5       n!U H$  n"U!R=                  U"R                  S#/ 5      5        M&     [;        5       n#U H$  n$U#R=                  U$R                  S#/ 5      5        M&     [?        U!U#5      n%U%US   S!   S$'   U Vs0 s H-  nUR                  S5      (       d  M  UR                  S5      U_M/     n&nU V"s/ s H+  n"U"R                  S5      U&;  d  M  U"R                  S5      PM-     n'n"U'US   S!   S%'   US   $ ! [        R                   a  n[        SU S	U S
35        Us SnA$ SnAff = fs  snf ! [&         a  nUs SnA$ SnAff = fs  snf s  sn"f )&a  A hook function to potentially add previous deployment diff information.

This function computes and adds Git-diff, package diff, and vulnerability diff
information between the current and the immediately preceding deployment event
for the same runtime, if the --show-previous-diff flag is set.

Args:
  response: The original response from the API, expected to be a
    DeploymentEvent object.
  args: Command line arguments.

Returns:
  The event dictionary, potentially modified with diff information.
)newPackagesrY   )newArtifactspackageDiffvulnerabilityDiff)
gitDiffUriartifactDiffspreviousDeploymentDiffrK   zDdeveloperconnect.projects.locations.insightsConfigs.deploymentEvents)
collectionz<--- AddPreviousDiffToResponse: Error parsing resource name 'z': z ---NruntimeConfigr5   developerconnectv1zruntime_config.uri = "rJ   i  )parentfilterpageSizec                 &    U R                  SS5      $ )Nr?    rA   )r$   s    r-   _SortKey+AddPreviousDiffToResponse.<locals>._SortKey^  s    >>,++r7   T)keyreverser0   zFound previous deployment: r   rz   z" Failed to construct Git Diff URI.zASkipping Git Diff computation due to parsing issues or same SHAs.z9Skipping Git Diff computation due to missing source URIs.r   r   r{   rx   r   ry   rw   ) show_previous_diffr   r   r   REGISTRYParseParentRelativeNameInvalidResourceExceptionr    r
   GetClientInstanceGetMessagesModuleKDeveloperconnectProjectsLocationsInsightsConfigsDeploymentEventsListRequest3projects_locations_insightsConfigs_deploymentEventsListdeploymentEventsr   r   	Exceptionr\   	enumeratelenrH   r6   r=   r   ri   rl   setupdatert   )(r!   r"   r$   r   current_deployment_nameresource_refinsights_config_parentr,   runtime_uriruntime_configclientmessageslist_requestlist_responseall_events_dictsr   sorted_eventscurrent_event_indexir#   previous_deploymentcurr_source_uriprev_source_uri	curr_baser<   	prev_baser;   git_diff_uricurrent_artifact_deploymentsprevious_artifact_deploymentsrE   r&   package_diffrp   curr_adrq   prev_advulnerability_diffprev_artifacts_mapnew_artifactss(                                           r-   AddPreviousDiffToResponser     sx    
	 	 O*LL' )+C!**%& 'NN62	 %%++Y , L *002??A +>>/2.**511 'K !!"4d;&##$6=(ee#%k]!4 f ,BBGG	
   006B66A 	!!!$6   
, )F- M*hayy33 + B 1s=11'(;a(?@	'(;(?(?(G'H
IJ .nn*B// .3R8/
 /@Ix/@Ix 	" ))XxHl	=I
+,\:23OP	
EF ",0Er!J"5"9"9R#
 )b66-.L|
",
+G\
B
Hb 	n ) *b66-.L|
",
+G\
B
Hb 	n * ,"$A,
  %&7
 7A8'B 5.-g'++&7<= . 5..g'++&7<= / 8n
  %&7 .-"	#	$ &bff !2%-   21'	(	)1C	C 'gkk%&1    %&7 
,	-- 
	+	+ 		$%S4	1 : 
 `
sf   <R 2R> 6 R9R> S$S SSR6R1+R61R69R> >
SS	SS)__doc__
__future__r   r   r   r2   apitools.base.pyr   r   r    googlecloudsdk.api_lib.artifactsr   (googlecloudsdk.api_lib.containeranalysisr	   rM   googlecloudsdk.api_lib.utilr
   googlecloudsdk.corer   r.   r6   r=   rH   r   ri   rl   rt   r   r9   r7   r-   <module>r      s\    H &  ' 	 % > < L , * )<~,,06&R,.
J.r7   