
    #                         d 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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  G d de      Zd Zd Z G d d      Zy)z=Helper functions for working with Apigee archive deployments.    )absolute_import)division)print_function)unicode_literalsN)apigee)errors)log)requests)resource_projector)archive)files)urllibc                       e Zd ZdZdZg dZej                  j                  ddd      Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zy)LocalDirectoryArchivezManages a local zip archive.zapigee_archive_deployment.zip)z.graphqlz.jarz.javaz.jsz.jscz.jsonz.oasz.propertiesz.pyz.securityPolicyz.wsdlz.xmlz.xsdz.xslz.yamlz.ymlsrcmainr   c                     | j                  |       |r4t        j                  j                  |      st	        j
                  |      ||nt        j                         | _        t        j                         | _
        y N)_CheckIfPathExistsospathisdirr   SourcePathIsNotDirectoryErrorr   GetCWD_src_dirTemporaryDirectory_tmp_dir)selfsrc_dirs     1lib/googlecloudsdk/command_lib/apigee/archives.py__init__zLocalDirectoryArchive.__init__<   sW    G$rww}}W-0099&2GDM,,.DM    c                     |rDt         j                  j                  |      s$t        j                  dj                  |            yy)z'Checks that the given file path exists.z-Path to archive deployment does not exist: {}N)r   r   existsr   MissingFileErrorformat)r   r   s     r    r   z(LocalDirectoryArchive._CheckIfPathExistsD   s>    BGGNN4(""
9
@
@
FH H )tr"   c                    |j                  | j                        syt        j                  j	                  |      \  }}t        j                  j                  | j                  |      }t        j                  j                  |      j                  d      ryt        j                  j                  |      ryt        j                  j                  |      r|j                         | j                  v ryy)zEFilter all files in the archive directory to only allow Apigee files.F.T)
startswith_ARCHIVE_ROOTr   r   splitextjoinr   basenamer   isfilelower_APIGEE_ARCHIVE_FILE_EXTENSIONS)r   	file_name_ext	full_paths        r    _ZipFileFilterz$LocalDirectoryArchive._ZipFileFilterJ   s     2 23WWi(FAsT]]I6I 
ww	"--c2 
ww}}Y
y!		t;;;r"   c                     t         j                  j                  | j                  j                  | j                        }t        j                  || j                  | j                         |S )z1Creates a zip archive of the specified directory.)	r   r   r,   r   _ARCHIVE_FILE_NAMEr   MakeZipFromDirr   r5   )r   dst_files     r    ZipzLocalDirectoryArchive.Zipa   sG    ww||DMM..0G0GHH8T]]D4G4GHOr"   c                 z    | j                  |       t        j                  |      st        j                  |      y)zCChecks that the zip file path exists and the file is a zip archvie.N)r   zipfile
is_zipfiler   BundleFileNotValidError)r   zip_paths     r    ValidateZipFilePathz)LocalDirectoryArchive.ValidateZipFilePathg   s4    H%h'**844 (r"   c                 6    | j                   j                         S )z&Deletes the local temporary directory.)r   Closer   s    r    rB   zLocalDirectoryArchive.Closem   s    ==  r"   c                     | S r    rC   s    r    	__enter__zLocalDirectoryArchive.__enter__q   s    Kr"   c                 ^    	 | j                          y #  t        j                  d       Y yxY w)Nz1Temporary directory was not successfully deleted.T)rB   r	   warning)r   exc_typevaltbs       r    __exit__zLocalDirectoryArchive.__exit__t   s'    
jjl	kkEFs    ,N)__name__
__module____qualname____doc__r7   r0   r   r   r,   r*   r!   r   r5   r:   r@   rB   rF   rL   rE   r"   r    r   r   #   sV    $ 7%!$ '',,ufh7-/H.5!r"   r   c                     t         j                  j                  |       }|j                  j	                  d      }|d   S )a  Helper function to extract the upload file id from the signed URL.

  Archive deployments must be uploaded to a provided signed URL in the form of:
  https://storage.googleapis.com/<bucket id>/<file id>.zip?<additional headers>
  This function extracts the file id from the URL (e.g., <file id>.zip).

  Args:
    upload_url: A string of the signed URL.

  Returns:
    A string of the file id.
  /)r   parseurlparser   split)
upload_urlurl
split_paths      r    GetUploadFileIdrZ   |   s4     	j)#xx~~c"*	Br"   c                     t        j                         }ddd}t        j                  |      5 }|j	                  | ||      }ddd       |S # 1 sw Y   S xY w)a-  Uploads the specified zip file with a PUT request to the provided URL.

  Args:
    upload_url: A string of the URL to send the PUT request to. Required to be a
      signed URL from GCS.
    zip_file: A string of the file path to the zip file to upload.

  Returns:
    A requests.Response object.
  zapplication/zipz0,1073741824)zcontent-typezx-goog-content-length-range)dataheadersN)r
   
GetSessionr   BinaryFileReaderput)rW   zip_filesessr]   r\   responses         r    UploadArchiverd      s\     
			$ (%3' h'4xx
wx?H (	/ (	/s   AAc                   "    e Zd ZdZd Zd Zd Zy)ListArchivesz5Adds additional helpful fields to a list of archives.c                     || _         t        j                  |      | _        d| _        d| _        d| _        d| _        d| _        d| _	        y )NDeployedzIn ProgressFailedz	Not FoundUnknownMissing)
_orgr   	LROPoller_lro_helper_deployed_status_inprogress_status_failed_status_not_found_status_unknown_status_missing_status)r   orgs     r    r!   zListArchives.__init__   sL    DI'',D&D+D"D(D$D$Dr"   c                 l   t        |d d      }d}t        |      D ]  \  }}t        j                  |      }|r| j                  |d<   nd|v rt
        j                  j                  d|d   i      d   }	 t
        j                  j                  | j                  |d	      }| j                  |      }	|	d
   |d<   |	d
   | j                  k(  r	|||<   |c S d|	v r|	d   |d<   n| j                  |d<   |||<    |S # t        j                  $ r | j                  |d<   Y - d}| j                  |d<   Y AxY w)zGiven a list of archives, extends them with a status and error field where needed.

    Args:
      archives: A list of archives to extend with a status and potential error.

    Returns:
      A list of archives with their associated status.
    c                     | d   S )N	createdAtrE   )ks    r    <lambda>z/ListArchives.ExtendedArchives.<locals>.<lambda>   s    +r"   T)keyreverseFoperationStatus	operationnameuuid)organizationsIdoperationsIdstatuserror)sorted	enumerater   MakeSerializablers   r   OperationsClient	SplitNameDescriberl   _StatusFromOperationro   r   EntityNotFoundErrorrr   rt   )
r   archivesextended_archivescascade_unknownidxaserilized_archiver   opr   s
             r    ExtendedArchiveszListArchives.ExtendedArchives   s~    .> O-.Q,==a@	/3/C/C+,!&&00&!K. 23 44:<	F&&//!%"1 " ,,R0&171A
-
.H!6!66%6c"$$& )/g& 04/C/C+,07 /8  )) 	H151G1G
-
.	F /151E1E
-
.s   6AC;C;;"D3D3c                     i }	 | j                   j                  |      }|r| j                  |d<   |S | j                  |d<   	 |S # t        j
                  $ r | j                  |d<   |d   d   |d<   Y |S w xY w)zGathers given an LRO, determines the associated archive status.

    Args:
      op: An Apigee LRO

    Returns:
      A dict in the format of
        {"status": "{status}", "error": "{error if present on LRO}"}.
    r   r   message)rn   IsDonero   rp   r   RequestErrorrq   )r   r   r   is_dones       r    r   z!ListArchives._StatusFromOperation   s     F/  ''+g	  00x M  22x M  /,,fX 7I.fWoM/s   ,A A -A54A5N)rM   rN   rO   rP   r!   r   r   rE   r"   r    rf   rf      s    =%0dr"   rf   )rP   
__future__r   r   r   r   r   r<   googlecloudsdk.api_libr   !googlecloudsdk.command_lib.apigeer   googlecloudsdk.corer	   r
   googlecloudsdk.core.resourcer   googlecloudsdk.core.utilr   r   	six.movesr   objectr   rZ   rd   rf   rE   r"   r    <module>r      sZ    D &  % ' 	  ) 4 # ( ; , * VF Vr$,Y Yr"   