o
    }$                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ G dd deZ	G d	d
 d
ej
Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )zUtilities for cloud resources.    )absolute_import)division)unicode_literalsN)
exceptionsc                   @   s   e Zd ZdZ	d ddZedd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zedd Zdd Zdd Zdd Zdd Zdd ZdS )!CollectionInfoa  Holds information about a resource collection.

  Attributes:
      api_name: str, name of the api of resources parsed by this parser.
      api_version: str, version id for this api.
      path: str, Atomic URI template for this resource.
      flat_paths: {name->path}, Named detailed URI templates for this resource.
        If there is an entry ''->path it replaces path and corresponding param
        attributes for resources parsing. path and params are not used in this
        case. Also note that key in this dictionary is referred as
        subcollection, as it extends 'name' attribute.
      params: list(str), description of parameters in the path.
      name: str, collection name for this resource without leading api_name.
      base_url: str, URL for service providing these resources.
      docs_url: str, URL to the API reference docs for this API.
      enable_uri_parsing: bool, whether to register a parser to build up a
        search tree to match URLs against URL templates.
  Tc
           
      C   s:   || _ || _|| _|| _|| _|| _|| _|| _|	| _d S N)	api_nameapi_versionbase_urldocs_urlnamepath
flat_pathsparamsenable_uri_parsing)
selfr   r	   r
   r   r   r   r   r   r    r   A/tmp/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/resource.py__init__.   s   

zCollectionInfo.__init__c                 C   s   | j d | j S )N.)r   r   r   r   r   r   	full_nameB   s   zCollectionInfo.full_namec                 C   s4   | j }||r|t|d d  S td||)N   z{0} does not exist in {1})r   
startswithlenKeyErrorformat)r   collection_namer   r   r   r   GetSubcollectionF   s   
zCollectionInfo.GetSubcollectionc                 C   s~   |  |}g }d}td|D ] }||||   |d |dr+|d | }q|t|kr:d|d< d|S )	z)Returns regex for matching path template.r   z({[^}]+}/)|({[^}]+})$z([^/]+)r   /z(.*)$ )	GetPathrefinditerappendstartgroupendr   join)r   subcollectionr   partsprev_endmatchr   r   r   GetPathRegExN   s   





zCollectionInfo.GetPathRegExc                 C   s   |s| j s| jS t| j | S )a  Returns ordered list of parameters for given subcollection.

    Args:
      subcollection: str, key name for flat_paths. If self.flat_paths is empty
        use '' (or any other falsy value) for subcollection to get default path
        parameters.

    Returns:
      Paramaters present in specified subcollection path.
    Raises:
      KeyError if given subcollection does not exists.
    )r   r   GetParamsFromPathr   r*   r   r   r   	GetParams]   s   
zCollectionInfo.GetParamsc                 C   s   |s| j s| jS | j | S )z2Returns uri template path for given subcollection.)r   r   r0   r   r   r   r"   o   s   

zCollectionInfo.GetPathc                 C   s$   | j |j ko| j|jko| j|jkS r   )r   r	   r   r   otherr   r   r   __eq__v   s
   

zCollectionInfo.__eq__c                 C   s
   | |k S r   r   r2   r   r   r   __ne__z   s   
zCollectionInfo.__ne__c                 C   s   ||k||k  S )z;Just a helper equivalent to the cmp() function in Python 2.r   )clsxyr   r   r   
_CmpHelper}   s   zCollectionInfo._CmpHelperc                 C   s(   |  | j| j| jf|j|j|jfdk S Nr   r9   r   r	   r   r2   r   r   r   __lt__   
   zCollectionInfo.__lt__c                 C   s(   |  | j| j| jf|j|j|jfdkS r:   r;   r2   r   r   r   __gt__   r=   zCollectionInfo.__gt__c                 C      |  | S r   )r>   r2   r   r   r   __le__      zCollectionInfo.__le__c                 C   r?   r   )r<   r2   r   r   r   __ge__   rA   zCollectionInfo.__ge__c                 C   s   | j S r   )r   r   r   r   r   __str__   s   zCollectionInfo.__str__N)T)__name__
__module____qualname____doc__r   propertyr   r   r.   r1   r"   r4   r5   classmethodr9   r<   r>   r@   rB   rC   r   r   r   r   r      s&    


r   c                       s    e Zd ZdZ fddZ  ZS )InvalidEndpointExceptionz0Exception for when an API endpoint is malformed.c                    s   t t| d| d S )Nz5URL does not start with 'http://' or 'https://' [{0}])superrJ   r   r   )r   url	__class__r   r   r      s   
z!InvalidEndpointException.__init__)rD   rE   rF   rG   r   __classcell__r   r   rM   r   rJ      s    rJ   c           	      C   s   t | d}t|}|d }|dkr4t|}t|dkr&|d |kr&d}nd}|dd||d fS || }d||d d }|dkrNt|||fS |dkrat|p[||d  }|||fS t| )aP  Returns api_name, api_version, resource_path tuple for an API URL.

  Supports the following formats:
  # Google API production/staging endpoints.
  http(s)://www.googleapis.com/{api}/{version}/{resource-path}
  http(s)://stagingdomain/{api}/{version}/{resource-path}
  http(s)://{api}.googleapis.com/{api}/{version}/{resource-path}
  http(s)://{api}.googleapis.com/apis/{kube-api.name}/{version}/{resource-path}
  http(s)://{api}.googleapis.com/{version}/{resource-path}
  http(s)://{api}.googleapis.com/{api}/{resource-path}
  http(s)://{api}.googleapis.com/{resource-path}
  http(s)://googledomain/{api}
  # Non-Google API endpoints.
  http(s)://someotherdomain/{api}/{version}/{resource-path}

  Args:
    url: str, The resource url.

  Returns:
    (str, str, str): The API name, version, resource_path.

  Raises: InvalidEndpointException.
  r   r   r    r      N)	_StripUrlsplit_GetApiVersionIndex_ExtractApiNameFromDomainr   r)   _FindKubernetesApiNamerJ   )	rL   tokensversion_indexdomainapiresource_indexversionresource_pathr   r   r   r   SplitEndpointUrl   s"   
r]   c                 C   sr   |  dd } |  d}g }|D ]&}|dr6|dr6|dd }|dr1||dd	  q|| q|S )
a/  Extract parameters from uri template path.

    See https://tools.ietf.org/html/rfc6570. This function makes simplifying
    assumption that all parameter names are surrounded by /{ and }/.

  Args:
    path: str, uri template path.

  Returns:
    list(str), list of parameters in the template path.
  :r   r   {}r   r    +N)rR   r   endswithr%   )r   r+   r   partr   r   r   r/      s   


r/   c                 C   s8   |  ds
|  dr| | dd d dS t| )zHStrip a http: or https: prefix, then strip leading and trailing slashes.zhttps://zhttp://r^   r   Nr   )r   indexstriprJ   )rL   r   r   r   rQ      s   rQ   c                 C   s    d}|D ]	}|| v r dS qdS )z2Check if the token parsed from Url is API version.)alphabetav1v2v3v4dogfoodheadTFr   )tokenversionsr	   r   r   r   IsApiVersion   s   rp   c                 C   s&   t | D ]\}}t|r|  S qdS )Nr    )	enumeraterp   )rV   idxrn   r   r   r   rS      s
   rS   c                 C   s   |  dd S )Nr   r   )rR   )rX   r   r   r   rT     s   rT   c                 C   s>   d}|  dd }|D ]}||ks|d| r|  S qdS )a>  Find the name of the kubernetes api.

  Determines the kubernetes api name from the domain of the resource uri.
  The domain may from a global resource or a regionalized resource.

  Args:
    domain: Domain from the resource uri.

  Returns:
    Api name. Returns None if the domain is not a kubernetes api domain.
  )runr   r   -N)rR   rb   )rX   k8s_api_namesdomain_first_partr   r   r   r   rU     s   rU   )rG   
__future__r   r   r   r#   googlecloudsdk.corer   objectr   ErrorrJ   r]   r/   rQ   rp   rS   rT   rU   r   r   r   r   <module>   s   z7	