
    -                     D   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mZ ddlZddl	Z	ddl
mZ dd	lmZ ddlZd
Zdj#                  e      Z e	j&                  e      ZdZ G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zd Zd Zd Zy)zResource definition generator.    )absolute_import)division)print_function)unicode_literals)OrderedDictN)resource)filesz)[a-zA-Z][a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)+z!(?P<collection>{collection})\.get)
collection c                       e Zd ZdZy)ErrorzErrors raised by this module.N__name__
__module____qualname____doc__     6lib/googlecloudsdk/api_lib/regen/resource_generator.pyr   r   &   s    %r   r   c                       e Zd ZdZy)NoMatchingMethodErrorz,Raised when no matching method can be found.Nr   r   r   r   r   r   *   s    4r   r   c                       e Zd ZdZy)UnsupportedDiscoveryDocz1Raised when some unsupported feature is detected.Nr   r   r   r   r   r   .   s    9r   r   c                       e Zd ZdZy)ConflictingCollectionz>Raised when collection names conflict and need to be resolved.Nr   r   r   r   r   r   2   s    Fr   r   c                       e Zd ZdZd Zed        Zed        Zed        Z	ed        Z
ed        Zd Zd	 Zd
 Z	 ddZd Zd Zy)DiscoveryDocz%Encapsulates access to discovery doc.c                     || _         y N_discovery_doc_dict)selfdiscovery_doc_dicts     r   __init__zDiscoveryDoc.__init__9   s
    1Dr   c                     t        j                  |      5 } | t        j                  |t                    cd d d        S # 1 sw Y   y xY w)N)object_pairs_hook)r	   
FileReaderjsonloadr   )clspathfs      r   FromJsonzDiscoveryDoc.FromJson<   s1    			$	11<= 
 		s   !AA
c                      | j                   d   S )Nnamer    r"   s    r   api_namezDiscoveryDoc.api_nameA   s    ##F++r   c                      | j                   d   S )Nversionr    r0   s    r   api_versionzDiscoveryDoc.api_versionE       ##I..r   c                      | j                   d   S )NbaseUrlr    r0   s    r   base_urlzDiscoveryDoc.base_urlI   r5   r   c                      | j                   d   S )NdocumentationLinkr    r0   s    r   docs_urlzDiscoveryDoc.docs_urlM   s    ##$788r   c                    | j                  || j                        }|rt        j                  |d   j                        d   }|D ]~  }|t        j                  |j                        d   k7  s)t        dj                  |j                  ||d   j                  |d   j                  |j                  |j                               |j                  | j                  |||             |S )a  Returns all resources collections found in this discovery doc.

    Args:
      custom_resources: {str, str}, A mapping of collection name to path that
          have been registered manually in the yaml file.
      api_version: Override api_version for each found resource collection.

    Returns:
      list(resource_util.CollectionInfo).

    Raises:
      UnsupportedDiscoveryDoc: if collections have different base URLs.
    r      zWIn client {0}/{1}, collection {2} is using url {3}, but collection {4} is using url {5})_ExtractResourcesr!   resource_utilSplitEndpointUrlr8   r   formatr1   r/   extend!_GenerateMissingParentCollections)r"   custom_resourcesr4   collectionsurl_api_versioncs         r   GetResourceCollectionsz#DiscoveryDoc.GetResourceCollectionsQ   s     ((T--/K%66
a.
!
!##$&o!m<<QZZHKK'006**a.%%a.))&&**1   ..);	89 r   c                 p   g }|j                  d      rG|j                  d      }|j                  d      }|r#| j                  ||      }|j                  |       |j                  d      rJ|j                  d      j                         D ](  \  }}| j	                  ||      }	|j                  |	       * |S )z0Extract resource definitions from discovery doc.methodsget	resources)rK   _GetCollectionFromMethodappenditemsr>   rB   )
r"   r4   infosrE   rJ   
get_methodcollection_info_infosubresource_collectionss
             r   r>   zDiscoveryDoc._ExtractResourcest   s    Kyy		)$g;;u%j	77%?+yyYY{+113'!T"&"8"8d"K23 4 r   c                     t        |d         }|j                  dd      d   }|j                  d      }|j                  d      }| j                  ||||      S )z>Created collection_info object given discovery doc get_method.id.r=   flatPathr+   )_ExtractCollectionNamesplitrK   _MakeResourceCollection)r"   r4   rQ   collection_name	flat_pathr+   s         r   rM   z%DiscoveryDoc._GetCollectionFromMethod   sb    ,Z-=>O &++C3A6Oz*I>>&!D''_dI r   Nc                 T   ||k(  rd}| j                   |z   }t        j                  |      \  }}}|r&t        j                  | j                   |z         \  }}}|dt        |        }t        j                  |||| j
                  |||rt        |ini t        j                  |            S )z8Make resource collection object given its name and path.N)r8   r?   r@   lenCollectionInfor;   DEFAULT_PATH_NAMEGetParamsFromPath)r"   r4   r]   r+   r^   urlurl_api_namerS   s           r   r\   z$DiscoveryDoc._MakeResourceCollection   s     Di
--$
C)::3?L!T%66
--)
#oaI kD	z
C''*3	I&''-	 	r   c                 l   |D ci c]  }|j                   | }}|D ch c]  }|j                  t               }}g }t        |      }g }	i }
|r|D ]  }t	        |      \  }}|s||v r||v r*|
j                  |t                     j                  |       G||v rJt        dj                  |j                  ||j                   |||   j                  t              |            | j                  ||d|      }|	j                  |       |||<   |j                  |        |j                  |	       |	}g }	|rt        j                  |
      D ]V  \  }}t!        |      dkD  r|j#                         }|||   d   k(  s1t%        dj                  || j                  |             X |S c c}w c c}w )a  Generates parent collections for any existing collection missing one.

    Args:
      collections: [resource.CollectionInfo], The existing collections from the
        discovery doc.
      custom_resources: {str, str}, A mapping of collection name to path that
        have been registered manually in the yaml file.
      api_version: Override api_version for each found resource collection.

    Raises:
      ConflictingCollection: If multiple parent collections have the same name
        but different paths, and a custom resource has not been declared to
        resolve the conflict.

    Returns:
      [resource.CollectionInfo], Additional collections to include in the
      resource module.
    zIn API [{api}/{version}], the parent of collection [{c}] is not registered, but a collection with [{parent_name}] and path [{existing_path}] already exists. Update the api config file to manually add the parent collection with a path of [{parent_path}].)apir3   rG   parent_nameexisting_pathparent_pathTr=   r+   z:WARNING: Custom resource [{}] in API [{}/{}] is redundant.)r/   GetPathrb   list_GetParentCollection
setdefaultsetaddr   rA   r1   MakeResourceCollectionrN   rB   six	iteritemsr`   popprint)r"   rE   rD   r4   rG   	all_names	all_paths	generatedin_progress
to_processignoredrh   rj   parent_collectionr/   pathsr+   s                    r   rC   z.DiscoveryDoc._GenerateMissingParentCollections   s   * %00KqKI07BC{!,-{ICI{#KJG
 !#7#: [
)#
**


[#%
0
4
4[
A
)# &! "(jj+)K(001BC)	 "( "+	, 	, !77dK9+,!2	+k"7 : z"kjE L }}W-e	Ua 	YY[d	!$'/	/KtT]]K8	; . o 1Cs
   F,F1c                 &   t        j                  | j                        \  }}}|r| j                  }ndj                  | j                  |      }t        j                  | j
                  ||| j                  ||i t        j                  |      |	      S )Nz{}{}/)r?   r@   r8   rA   ra   r1   r;   rc   )r"   r]   r+   enable_uri_parsingr4   rS   rF   r8   s           r   rq   z#DiscoveryDoc.MakeResourceCollection   sx    )::4==IAh{;h''{Hdmmr=#B#B4#H r   r   )r   r   r   r   r$   classmethodr-   propertyr1   r4   r8   r;   rH   r>   rM   r\   rC   rq   r   r   r   r   r   6   s    -2 > > , , / / / / 9 9!F"
 ;?8L\
r   r   c                     t         j                  |       }|r|j                  d      S t        dj	                  | t
                    )z4Extract the name of the collection from a method ID.r
   z%Method {0} does not match regexp {1}.)_METHOD_ID_REmatchgroupr   rA   _METHOD_ID_RE_RAW)	method_idr   s     r   rZ   rZ     sA    


i
(%
;;|$$
/		,	-/ /r   c                    | j                  t              }t        |      dk  ry| j                  t              }|j	                  d      }t        |d       t        |d       |sydj                  |      }t        |d       |syd| j                  v r#| j                  j                  dd      \  }}||fS |d   }||fS )	a  Generates the name and path for a parent collection.

  Args:
    collection_info: resource.CollectionInfo, The collection to calculate the
      parent of.

  Returns:
    (str, str), A tuple of parent name and path or (None, None) if there is no
    parent.
     )NN/TFrX   r=   )		GetParamsrb   r`   rk   r[   _PopSegmentsjoinr/   rsplit)rR   paramsr+   partsrj   rh   rS   s          r   rm   rm     s     $$%67&[1_		 	 !2	3$ **S/%udue	+ ud	O    %))00a8NK
 
k	!! )K	k	!!r   c                     | rt| d   j                  d      |k(  r\| d   j                  d      |k(  rD| j                          | sy | d   j                  d      |k(  r| d   j                  d      |k(  rBy y y y y )Nr   {})
startswithendswithrt   )r   	is_paramss     r   r   r   A  s    
9$	19c"i/iik	 9$	19c"i/ 2/ 2 r   ) r   
__future__r   r   r   r   rE   r   r(   regooglecloudsdk.api_lib.utilr   r?   googlecloudsdk.core.utilr	   rr   _COLLECTION_SUB_RErA   r   compiler   rb   	Exceptionr   r   r   r   objectr   rZ   rm   r   r   r   r   <module>r      s    % &  % ' #  	 A * 
 B 8??! @ # 

,- &I &5E 5:e :GE GO6 Od/+"\r   