
    ;                        d Z ddlmZ ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlmZ ddlmc mc mZ ddlmc mc mZ  G d de      Z G d d	e      Zd
 Z G d de      Zej<                  dd       Zd Z d Z! G d d ejD                  dd            Z#d Z$d Z% G d de      Z&d Z'd Z(d Z)ddZ*y)z4Assorted utilities shared between parts of apitools.    )print_function)unicode_literalsN)urllib_parsec                       e Zd ZdZy)Errorz#Base error for apitools generation.N__name__
__module____qualname____doc__     $lib/third_party/apitools/gen/util.pyr   r   %   s    -r   r   c                       e Zd ZdZy)CommunicationErrorzError in network communication.Nr   r   r   r   r   r   *   s    )r   r   c                     t        |        | fS N)len)as    r   _SortLengthFirstKeyr   /   s    F7A:r   c                       e Zd ZdZdZg dZ	 	 ddZedd       Zedd       Z	edd       Z
d	 Zed
        Zed        Zd ZddZddZd Zy)NameszBUtility class for cleaning and normalizing names in a fixed style.LOWER_CAMEL)r   LOWER_WITH_UNDERNONENc                 h    t        |t              | _        |xs | j                  | _        || _        y )N)key)sortedr   _Names__strip_prefixesDEFAULT_NAME_CONVENTION_Names__name_convention_Names__capitalize_enums)selfstrip_prefixesname_conventioncapitalize_enumss       r   __init__zNames.__init__9   s2     !'~;N O;t;; 	"2r   c                 V    t        j                  dd|z  |       } | j                         S )Nz([a-z0-9])([A-Z])z\1%s\2)resublowername	separators     r   __FromCamelzNames.__FromCamelA   s&    vv*I	,A4Hzz|r   c                 P    dj                  d | j                  |      D              S )N c              3   N   K   | ]  }|d d j                         |dd z     yw)r      N)upper).0ss     r   	<genexpr>z"Names.__ToCamel.<locals>.<genexpr>J   s*     M7L!q1v||~!"-7Ls   #%)joinsplitr,   s     r   	__ToCamelzNames.__ToCamelF   s"     wwMtzz)7LMMMr   c                 b    t         j                  | |      } | d   j                         | dd  z   S )Nr.   r   r3   )r   _Names__ToCamelr+   r,   s     r   __ToLowerCamelzNames.__ToLowerCamelL   s/    ty9Aw}}ab))r   c                 r    |s|S | j                   D ]#  }|j                  |      s|t        |      d c S  |S )z%Strip strip_prefix entries from name.N)r   
startswithr   )r#   r-   prefixs      r   __StripNamezNames.__StripNameQ   s>    K++Fv&CKL)) , r   c                    t        j                  dd|       } | d   j                         rd| z  } t        j                  |       s| dk(  r!d| z  } t        j                  |       r| dk(  r!| j                  d      rd| z  } | S )	zPerform generic name cleaning.z[^_A-Za-z0-9]_r   z_%sexecz%s___zf%s)r)   r*   isdigitkeyword	iskeywordr@   )r-   s    r   	CleanNamezNames.CleanNameZ   s|     vvosD17??4<D%4<D % ??4 4<Dr   c           	          | j                  d      }g }|D ]T  }t        j                  d|      r+|j                  dt        j                  |dd       z         D|j                  |       V dj                  |      S )z$Normalize camelCase entries in path./z{[A-Za-z0-9_]+}$z{%s}r3   )r9   r)   matchappendr   rJ   r8   )pathpath_componentsnormalized_components	components       r   NormalizeRelativePathzNames.NormalizeRelativePathh   sw     **S/ "(Ixx+Y7%,,U__Yq_==? &,,Y7 ) xx-..r   c                 \    | j                   r|j                         }| j                  |      S r   )r"   r4   rJ   )r#   	enum_names     r   NormalizeEnumNamezNames.NormalizeEnumNameu   s&    ""!)I~~i((r   c                     ||S |j                  d      r|S | j                  |      }| j                  ||      }| j                  |      S )z&Generate a valid class name from name.)z	protorpc.zmessage_types.zapitools.base.protorpclite.z)apitools.base.protorpclite.message_types.r<   )r@   _Names__StripNamer=   rJ   r#   r-   r.   s      r   	ClassNamezNames.ClassNamez   s[     <K ?? I J K%~~di~8~~d##r   c                 `    |yt         j                  ||      }t         j                  |      S )z'Generate a valid method name from name.Nr<   )r   r=   rJ   rZ   s      r   
MethodNamezNames.MethodName   s+    <ty9t$$r   c                     | j                  |      }| j                  dk(  rt        j                  |      }n$| j                  dk(  rt        j	                  |      }t        j                  |      S )z&Generate a valid field name from name.r   r   )rY   r!   r   _Names__ToLowerCamel_Names__FromCamelrJ   )r#   r-   s     r   	FieldNamezNames.FieldName   s`    
 %!!]2''-D##'99$$T*Dt$$r   )NF)rD   )r	   r
   r   r   r    NAME_CONVENTIONSr'   staticmethodr`   r=   r_   rY   rJ   rT   rW   r[   r]   ra   r   r   r   r   r   3   s    L+B "&"'3   N N
 * *   
/ 
/)
$%
%r   r   c              #   N  K   t         j                  j                  |       s%|st        d| z        t        j                  |        t        j
                         }	 t        j                  |        d  t        j                  |       y # t        j                  |       w xY ww)NzCannot find directory %s)osrP   existsOSErrormkdirgetcwdchdir)dirnamecreateprevious_directorys      r   Chdirrn      sp     77>>'"4w>??HHW%

#$#$s   AB%B 5B%B""B%c                 &    | j                  dd      S )N.rD   )replace)versions    r   NormalizeVersionrs      s    ??3$$r   c                     t        j                  ||      }dj                  | |df      }||vr|dfS |j                  |      \  }}}||z   |fS )a1  Compute the base url and base path.

    Attributes:
      package: name field of the discovery, i.e. 'storage' for storage service.
      version: version of the service, i.e. 'v1'.
      root_url: root url of the service, i.e. 'https://www.googleapis.com/'.
      service_path: path of the service under the rool url, i.e. 'storage/v1/'.

    Returns:
      base url: string, base url of the service,
        'https://www.googleapis.com/storage/v1/' for the storage service.
      base path: string, common prefix of service endpoints after the base url.
    rL   r1   )r   urljoinr8   
rpartition)	packagerr   root_urlservice_path	full_pathapi_path_componentrA   rD   suffixs	            r   _ComputePathsr}      sg     $$X|<I7GR"89*"}!,,-?@FAv&&..r   c                       e Zd ZdZed        Zed        Zed        Zed        Z	ed        Z
ed        Zed        Zed	        Zed
        Zy)
ClientInfoz,Container for client-related info and names.c	                    t        |j                  di       j                  di       j                  di             }	|	j                  |       |d   }
|xs t        |d         }|d   }t	        |
||d   |d         \  }}|j                  dd	      }d	}|rt	        |
|||d         \  }}|
||t        t        |	            |||||||d
}|j                  |d         |j                  |d         }||d<    | di |S )z9Create a new ClientInfo object from a discovery document.authoauth2scopesr-   rr   rootUrlservicePathmtlsRootUrlr1   )rw   rr   url_versionr   	client_idclient_secret
user_agentapi_keybase_url	base_pathmtls_base_urlrw   client_class_namer   )setgetupdaters   r}   r   listr[   )clsdiscovery_docscope_lsr   r   r   namesr   version_identifierr   rw   rr   r   r   r   mtls_root_urlr   rD   client_infor   s                       r   CreatezClientInfo.Create   sJ   
 fb)--h;??"MOh'L"2=3K"L 	#I.+G[,9),D,9-,HJ) &))-<,Wk-:-:=-I KM1
 &T&\*"*$ "*
 OOK	23OOK	235 ,='(![!!r   c                     | j                   S r   )rw   r#   s    r   default_directoryzClientInfo.default_directory   s    ||r   c                 :    | j                   d| j                  dS )NrD   _clientrw   rr   r   s    r   client_rule_namezClientInfo.client_rule_name   s    !%t||<<r   c                      d| j                   z  S Nz%s.py)r   r   s    r   client_file_namezClientInfo.client_file_name   s    ....r   c                 :    | j                   d| j                  dS )NrD   	_messagesr   r   s    r   messages_rule_namezClientInfo.messages_rule_name      #'<<>>r   c                 :    | j                   d| j                  dS )NrD   	_servicesr   r   s    r   services_rule_namezClientInfo.services_rule_name  r   r   c                      d| j                   z  S r   r   r   s    r   messages_file_namezClientInfo.messages_file_name  s    0000r   c                      d| j                   z  S Nz%s.protor   r   s    r   messages_proto_file_namez#ClientInfo.messages_proto_file_name      D3333r   c                      d| j                   z  S r   )r   r   s    r   services_proto_file_namez#ClientInfo.services_proto_file_name  r   r   N)r	   r
   r   r   classmethodr   propertyr   r   r   r   r   r   r   r   r   r   r   r   r      s    
 7'" '"R   = = / / ? ? ? ? 1 1 4 4 4 4r   r   )rw   r   rr   r   r   r   r   r   r   r   r   r   c                     ddddddddddddd	fd
}dj                  | D cg c]
  } ||       c}      S c c}w )z@Returns s with unicode homoglyphs replaced by ascii equivalents. r1   z(C)z(R)-'"z...)       ãr      ©   ®u   —u   ‘u   ’u   “u   ”u   …u   ⸺c                     j                  |       }||S 	 | j                  d       | S # t        $ r Y nw xY w	 | j                  d      j                  d      S # t        $ r Y yw xY w)z3Returns the homoglyph or escaped replacement for c.asciizunicode-escape?)r   encodeUnicodeErrordecode)cequiv
homoglyphss     r   _ReplaceOnez&ReplaceHomoglyphs.<locals>._ReplaceOne*  sv    q!L	HHWH 			88,-44W== 		s   + 	77A 	A'&A')r8   )r6   r   r   r   s      @r   ReplaceHomoglyphsr     s\     J 77A.AqKNA.//.s   ;c                     t        | t        j                        s| S t        j                  r6| j	                  dd      } | j	                  dd      } | j	                  dd      } t        |       } | j	                  dd      S )	zAReturn a version of description safe for printing in a docstring.z\Nz\\Nz\uz\\uz\Uz\\Uz"""z" " ")
isinstancesixstring_typesPY3rq   r   )descriptions    r   CleanDescriptionr   <  sr    k3#3#34
ww!))%9!))%9!))%9#K0Kug..r   c                   ~    e Zd ZdZd Zed        Zd	dZej                  d
d       Z
ej                  d        Zd Zy)SimplePrettyPrinterz=Simple pretty-printer that supports an indent contextmanager.c                 <    || _         d| _        d| _        d| _        y )Nr1   F)_SimplePrettyPrinter__out_SimplePrettyPrinter__indent_SimplePrettyPrinter__skip%_SimplePrettyPrinter__comment_context)r#   outs     r   r'   zSimplePrettyPrinter.__init__M  s    
!&r   c                     | j                   S r   r   r   s    r   indentzSimplePrettyPrinter.indentS  s    }}r   c                 2    |t        | j                        z
  S r   )r   r   )r#   	max_widths     r   CalculateWidthz"SimplePrettyPrinter.CalculateWidthW  s    3t{{+++r   c              #   P   K   | j                   }||| _         d  || _         y wr   r   )r#   r   previous_indents      r   IndentzSimplePrettyPrinter.IndentZ  s%     --"16:'s   $&c              #   H   K   | j                   }d| _         d || _         yw)z&Print without any argument formatting.TN)r   )r#   old_contexts     r   CommentContextz"SimplePrettyPrinter.CommentContexta  s&      ,,!%!,s    "c                    | j                   r|dd  rt        d      |rp|d   rk| j                   s|d   |dd  z  j                         }n|d   j                         }t        |      }	 t	        | j
                  || j                         y t	        d| j                         y # t        $ rI |j                  dd      j                  d      }t	        | j
                  || j                         Y y w xY w)Nr3   z1Cannot do string interpolation in comment contextr   )filer   backslashreplacer1   )
r   r   rstripr   printr   r   UnicodeEncodeErrorr   r   )r#   argslines      r   __call__zSimplePrettyPrinter.__call__i  s    !!d12hKLLDG))Q$qr(*224Aw~~'$T*DGt44::F
 "4::&	 & G{{7,>?FFwOt44::FGs   )%B' 'AC98C9N)N   )z  )r	   r
   r   r   r'   r   r   r   
contextlibcontextmanagerr   r   r   r   r   r   r   r   I  s\    G'  , ( ( - -'r   r   c                     | j                  d      r| gS d| vrt        d      | j                  d      \  }}}d|d|dd|d|gS )	z5Expands a few abbreviations into full discovery urls.httprp   z)Unrecognized value "%s" for discovery urlz-https://www.googleapis.com/discovery/v1/apis/rL   z/restzhttps://z(.googleapis.com/$discovery/rest?version=)r@   
ValueError	partition)discovery_urlapi_namerD   api_versions       r   _NormalizeDiscoveryUrlsr   {  se    '	M	!DEE,66s;Ha k	# k	# r   c                    t        j                  ddd      }	 |j                  |        |j                          t	        j
                  |j                  d      5 }|j                         }ddd       t        j                  |j                         S # 1 sw Y   *xY w# t        j                  |j                         w xY w)z0Returns gunzipped content from gzipped contents.gzzw+bF)r|   modedeleterbN)
tempfileNamedTemporaryFilewriteclosegzipopenr-   readre   unlink)gzipped_contentfhdecompressed_contents       r   _Gunzipr    s    ##4eEJA	 		YYqvvt$#$668  %#
		!&&	 %$ 			!&&s$   AB! B,	B! BB! !!Cc                     t        j                  |       }|j                         j                  d      }|dk(  rt	        |j                               }|S |j                         }|S )z'Download and return the content of URL.zContent-Encodingr  )urllib_requesturlopeninfor   r  r  )urlresponseencodingcontents       r   _GetURLContentr    sZ    %%c*H}}""#56H6(--/* N --/Nr   c                    t        |       }d}d}|D ]\  }t        |      D ]L  }	 t        |      }t        |t              r|j                  d      }t        j                  |      }|r|c c S N ^ |t        d|d|      y# t        j                  t        j                  f$ r"}t        j                  d|       |}Y d}~d}~ww xY w)z.Fetch the discovery document at the given url.Nutf8z2Attempting to fetch discovery doc again after "%s"z'Could not find discovery doc at any of z: )r   ranger  r   bytesr   jsonloadsurllib_error	HTTPErrorURLErrorloggingr  r   )	r   retriesdiscovery_urlsr   last_exceptionr  rD   r  es	            r   FetchDiscoveryDocr$    s    ,];NMNwA
#(-gu-%nnV4G $

7 3 (( !     01 	1 	 !**L,A,AB #H!M!"#s   AB#C
(CC
)T)   )+r   
__future__r   r   collectionsr   r  r  rH   r  re   r)   r   r   	six.movesr   six.moves.urllib.errormovesurlliberrorr  six.moves.urllib.requestrequestr  	Exceptionr   r   r   objectr   r   rn   rs   r}   
namedtupler   r   r   r   r   r  r  r$  r   r   r   <module>r2     s   " ; % '       	 	  
 " - - 1 1.I .
* *
g%F g%T % %%
/,O4''' 72 3 O4d 0F
//'& /'d
1r   