o
    ˷eH                     @   s  U d 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	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 z
ddlZddlZW n eyR   dZY nw ejjZejjZejdd	d	ejjd
ZdZdZdZdZ e!dej"Z#ee$df e%d< zej&'dZ(W n ey   dZ(Y nw ej&)dddZ*dZ+dZ,G dd deZ-dd Z.dJddZ/dd Z0dd  Z1d!d" Z2d#d$ Z3d%d& Z4d'd( Z5d)d* Z6d+d, Z7dKd.d/Z8dLd1d2Z9d3d4 Z:d5d6 Z;d7d8 Z<d9d: Z=d;d< Z>d=d> Z?d?d@ Z@dAdB ZAdMdDdEZBdMdFdGZCdJdHdIZDdS )Nz^Shared helpers for Google Cloud packages.

This module is not part of the public API surface.
    )absolute_importN)local)Union)duration_pb2)timestamp_pb2i     tzinfoz%Y-%m-%dT%H:%M:%S.%fZz%Y-%m-%dT%H:%M:%Sz%H:%M:%S.%fz%H:%M:%Sah  
    (?P<no_fraction>
        \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}  # YYYY-MM-DDTHH:MM:SS
    )
    (                                        # Optional decimal part
     \.                                      # decimal point
     (?P<nanos>\d{1,9})                      # nanoseconds, maybe truncated
    )?
    Z                                        # Zulu

_USER_ROOT~gcloudconfigurationsconfig_defaultcoreprojectc                       sD   e Zd ZdZ fddZdd Zdd Zdd	 Zed
d Z	  Z
S )_LocalStackzManage a thread-local LIFO stack of resources.

    Intended for use in :class:`google.cloud.datastore.batch.Batch.__enter__`,
    :class:`google.cloud.storage.batch.Batch.__enter__`, etc.
    c                    s   t t|   g | _d S N)superr   __init___stackself	__class__ U/var/www/ideatree/venv/lib/python3.10/site-packages/google/cloud/_helpers/__init__.pyr   S   s   
z_LocalStack.__init__c                 C   s   t t| jS )z Iterate the stack in LIFO order.)iterreversedr   r   r   r   r   __iter__W   s   z_LocalStack.__iter__c                 C   s   | j | dS )zPush a resource onto our stack.N)r   append)r   resourcer   r   r   push[   s   z_LocalStack.pushc                 C   s
   | j  S )zPop a resource from our stack.

        :rtype: object
        :returns: the top-most resource, after removing it.
        :raises IndexError: if the stack is empty.
        )r   popr   r   r   r   r"   _   s   
z_LocalStack.popc                 C   s   | j r| j d S dS )z~Get the top-most resource

        :rtype: object
        :returns: the top-most item, or None if the stack is empty.
        N)r   r   r   r   r   toph   s   
z_LocalStack.top)__name__
__module____qualname____doc__r   r   r!   r"   propertyr$   __classcell__r   r   r   r   r   L   s    	r   c                 C   s&   t |ttfstd| |f t|S )a  Ensures an input is a tuple or list.

    This effectively reduces the iterable types allowed to a very short
    whitelist: list and tuple.

    :type arg_name: str
    :param arg_name: Name of argument to use in error message.

    :type tuple_or_list: sequence of str
    :param tuple_or_list: Sequence to be verified.

    :rtype: list of str
    :returns: The ``tuple_or_list`` passed in cast to a ``list``.
    :raises TypeError: if the ``tuple_or_list`` is not a tuple or list.
    z.Expected %s to be a tuple or list. Received %r)
isinstancetuplelist	TypeError)arg_nametuple_or_listr   r   r   _ensure_tuple_or_lists   s   r1   c                 C   s   | du rt j \}} | S )aY  Determine default project ID explicitly or implicitly as fall-back.

    See :func:`google.auth.default` for details on how the default project
    is determined.

    :type project: str
    :param project: Optional. The project name to use as default.

    :rtype: str or ``NoneType``
    :returns: Default project if it can be determined.
    N)googleauthdefault)r   _r   r   r   _determine_default_project   s   r6   c                 C   s   t | }|d S )zConvert a zone-aware datetime to integer milliseconds.

    :type when: :class:`datetime.datetime`
    :param when: the datetime to convert

    :rtype: int
    :returns: milliseconds since epoch for ``when``
      )_microseconds_from_datetime)whenmicrosr   r   r   _millis      	r;   c                 C   s   t tj| d S )zConvert timestamp to datetime, assuming UTC.

    :type value: float
    :param value: The timestamp to convert

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the value.
    )microseconds)_EPOCHdatetime	timedeltavaluer   r   r   _datetime_from_microseconds   s   	rC   c                 C   s8   | j s	| jtd} | t} tt|  d | j S )zConvert non-none datetime to microseconds.

    :type value: :class:`datetime.datetime`
    :param value: The timestamp to convert.

    :rtype: int
    :returns: The timestamp, in microseconds.
    r   g    .A)	r	   replaceUTC
astimezoneintcalendartimegm	timetuplemicrosecondrA   r   r   r   r8      s   	
r8   c                 C   s   | durt | S dS )zConvert non-none datetime to timestamp, assuming UTC.

    :type value: :class:`datetime.datetime`
    :param value: (Optional) the timestamp

    :rtype: int, or ``NoneType``
    :returns: the timestamp, in milliseconds, or None
    N)r;   rA   r   r   r   _millis_from_datetime   s   	rL   c                 C   s   t j | d S )zConvert a ISO8601 date string to native datetime date

    :type value: str
    :param value: The date string to convert

    :rtype: :class:`datetime.date`
    :returns: A datetime date object created from the string

    z%Y-%m-%d)r?   strptimedaterA   r   r   r   _date_from_iso8601_date   s   
rO   c                 C   sD   t | dkr	t}nt | dkrt}ntd| tj| | S )a*  Convert a zoneless ISO8601 time string to naive datetime time

    :type value: str
    :param value: The time string to convert

    :rtype: :class:`datetime.time`
    :returns: A datetime time object created from the string
    :raises ValueError: if the value does not match a known format.
          zUnknown time format: {})len_TIMEONLY_NO_FRACTION_TIMEONLY_W_MICROS
ValueErrorformatr?   rM   time)rB   fmtr   r   r   _time_from_iso8601_time_naive   s   
rY   c                 C   s   t j | tjtdS )zConvert a microsecond-precision timestamp to a native datetime.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    r   )r?   rM   _RFC3339_MICROSrD   rE   )dt_strr   r   r   _rfc3339_to_datetime   s   	r\   c                 C   s   t | }|du rtd| t jf tj|dt}|d}|du r(d}ndt| }t	|d|  }|d }|j
|td	S )
a  Convert a nanosecond-precision timestamp to a native datetime.

    .. note::

       Python datetimes do not support nanosecond precision;  this function
       therefore truncates such values to microseconds.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    :raises ValueError: If the timestamp does not match the RFC 3339
                        regular expression.
    Nz)Timestamp: %r, does not match pattern: %rno_fractionnanosr   	   
   r7   )rK   r	   )_RFC3339_NANOSmatchrU   patternr?   rM   group_RFC3339_NO_FRACTIONrR   rG   rD   rE   )r[   
with_nanosbare_secondsfractionr:   scaler^   r   r   r   _rfc3339_nanos_to_datetime   s"   


rj   Tc                 C   s,   |s| j dur| jdd|   } | tS )at  Convert a timestamp to a string.

    :type value: :class:`datetime.datetime`
    :param value: The datetime object to be converted to a string.

    :type ignore_zone: bool
    :param ignore_zone: If True, then the timezone (if any) of the datetime
                        object is ignored.

    :rtype: str
    :returns: The string representing the datetime stamp.
    Nr   )r	   rD   	utcoffsetstrftimerZ   )rB   ignore_zoner   r   r   _datetime_to_rfc3339"  s   
rn   asciic                 C   s4   t | tr
| |n| }t |tr|S td| f )a'  Converts a string value to bytes, if necessary.

    :type value: str / bytes or unicode
    :param value: The string/bytes value to be converted.

    :type encoding: str
    :param encoding: The encoding to use to convert unicode to bytes. Defaults
                     to "ascii", which will not allow any characters from
                     ordinals larger than 127. Other useful values are
                     "latin-1", which which will only allows byte ordinals
                     (up to 255) and "utf-8", which will encode any unicode
                     that needs to be.

    :rtype: str / bytes
    :returns: The original value converted to bytes (if unicode) or as passed
              in if it started out as bytes.
    :raises TypeError: if the value could not be converted to bytes.
    z"%r could not be converted to bytes)r+   strencodebytesr.   )rB   encodingresultr   r   r   	_to_bytes6  s   
ru   c                 C   s4   t | tr
| dn| }t |tr|S td| f )ac  Converts bytes to a unicode value, if necessary.

    :type value: bytes
    :param value: bytes value to attempt string conversion on.

    :rtype: str
    :returns: The original value converted to unicode (if bytes) or as passed
              in if it started out as unicode.

    :raises ValueError: if the value could not be converted to unicode.
    zutf-8z$%r could not be converted to unicode)r+   rr   decoderp   rU   )rB   rt   r   r   r   _bytes_to_unicodeP  s   
rw   c                 C   s*   |  }| |std|jj| j|S )ay  Converts an Any protobuf to the specified message type

    Args:
        pb_type (type): the type of the message that any_pb stores an instance
            of.
        any_pb (google.protobuf.any_pb2.Any): the object to be converted.

    Returns:
        pb_type: An instance of the pb_type message.

    Raises:
        TypeError: if the message could not be converted.
    zCould not convert {} to {})Unpackr.   rV   r   r%   )pb_typeany_pbmsgr   r   r   _from_any_pbc  s   

r|   c                 C   s   t tj| j| jd d S )a1  Convert a Timestamp protobuf to a datetime object.

    :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :param timestamp_pb: A Google returned timestamp protobuf.

    :rtype: :class:`datetime.datetime`
    :returns: A UTC datetime object converted from a protobuf timestamp.
         @@secondsr=   )r>   r?   r@   r   r^   )timestamp_pbr   r   r   _pb_timestamp_to_datetime|  s   	r   c                 C   s   t | }t|S )a  Convert a Timestamp protobuf to an RFC 3339 string.

    :type timestamp_pb: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :param timestamp_pb: A Google returned timestamp protobuf.

    :rtype: str
    :returns: An RFC 3339 formatted timestamp string.
    )r   rn   )r   	timestampr   r   r   _pb_timestamp_to_rfc3339  r<   r   c                 C   s,   t | }t|d\}}|d }tj||dS )a
  Convert a datetime object to a Timestamp protobuf.

    :type when: :class:`datetime.datetime`
    :param when: the datetime to convert

    :rtype: :class:`google.protobuf.timestamp_pb2.Timestamp`
    :returns: A timestamp protobuf corresponding to the object.
    i@B r7   )r   r^   )r8   divmodr   	Timestamp)r9   ms_valuer   r:   r^   r   r   r   _datetime_to_pb_timestamp  s   	r   c                 C   s   t  }||  |S )a  Convert a Python timedelta object to a duration protobuf.

    .. note::

        The Python timedelta has a granularity of microseconds while
        the protobuf duration type has a duration of nanoseconds.

    :type timedelta_val: :class:`datetime.timedelta`
    :param timedelta_val: A timedelta object.

    :rtype: :class:`google.protobuf.duration_pb2.Duration`
    :returns: A duration object equivalent to the time delta.
    )r   DurationFromTimedelta)timedelta_valduration_pbr   r   r   _timedelta_to_duration_pb  s   
r   c                 C   s   t j| j| jd dS )a  Convert a duration protobuf to a Python timedelta object.

    .. note::

        The Python timedelta has a granularity of microseconds while
        the protobuf duration type has a duration of nanoseconds.

    :type duration_pb: :class:`google.protobuf.duration_pb2.Duration`
    :param duration_pb: A protobuf duration object.

    :rtype: :class:`datetime.timedelta`
    :returns: The converted timedelta object.
    r}   r~   )r?   r@   r   r^   )r   r   r   r   _duration_pb_to_timedelta  s   r   c                 C   sh   t |tr
t|}|| }|std| |jf |dur/|d}||kr/td||f |dS )a  Validate a URI path and get the leaf object's name.

    :type path: str
    :param path: URI path containing the name.

    :type project: str
    :param project: (Optional) The project associated with the request. It is
                    included for validation purposes.  If passed as None,
                    disables validation.

    :type template: str
    :param template: Template regex describing the expected form of the path.
                     The regex must have two named groups, 'project' and
                     'name'.

    :rtype: str
    :returns: Name parsed from ``path``.
    :raises ValueError: if the ``path`` is ill-formed or if the project from
                        the ``path`` does not agree with the ``project``
                        passed in.
    z-path "%s" did not match expected pattern "%s"Nr   zEProject from client (%s) should agree with project from resource(%s).name)r+   rp   recompilerb   rU   rc   rd   )pathr   templaterb   found_projectr   r   r   _name_from_project_path  s    




r   r   c                 C   sH   d|t jjf }tjjj }d|f}|f| }tjjjj	| |||dS )a  Makes a secure channel for an RPC service.

    Uses / depends on gRPC.

    :type credentials: :class:`google.auth.credentials.Credentials`
    :param credentials: The OAuth2 Credentials to use for creating
                        access tokens.

    :type user_agent: str
    :param user_agent: The user agent to be used with API requests.

    :type host: str
    :param host: The host for the service.

    :type extra_options: tuple
    :param extra_options: (Optional) Extra gRPC options used when creating the
                          channel.

    :rtype: :class:`grpc._channel.Channel`
    :returns: gRPC secure channel with credentials attached.
    %s:%dzgrpc.primary_user_agent)options)
httpclient
HTTPS_PORTr2   r3   	transportrequestsRequestgrpcsecure_authorized_channel)credentials
user_agenthostextra_optionstargethttp_requestuser_agent_optionr   r   r   r   make_secure_channel  s   

r   c                 C   s   t | |||d}||S )a  Makes a secure stub for an RPC service.

    Uses / depends on gRPC.

    :type credentials: :class:`google.auth.credentials.Credentials`
    :param credentials: The OAuth2 Credentials to use for creating
                        access tokens.

    :type user_agent: str
    :param user_agent: The user agent to be used with API requests.

    :type stub_class: type
    :param stub_class: A gRPC stub type for a given service.

    :type host: str
    :param host: The host for the service.

    :type extra_options: tuple
    :param extra_options: (Optional) Extra gRPC options passed when creating
                          the channel.

    :rtype: object, instance of ``stub_class``
    :returns: The stub object used to make gRPC requests to a given API.
    )r   )r   )r   r   
stub_classr   r   channelr   r   r   make_secure_stub  s   r   c                 C   s,   |du r|}nd||f }t |}| |S )a  Makes an insecure stub for an RPC service.

    Uses / depends on gRPC.

    :type stub_class: type
    :param stub_class: A gRPC stub type for a given service.

    :type host: str
    :param host: The host for the service. May also include the port
                 if ``port`` is unspecified.

    :type port: int
    :param port: (Optional) The port for the service.

    :rtype: object, instance of ``stub_class``
    :returns: The stub object used to make gRPC requests to a given API.
    Nr   )r   insecure_channel)r   r   portr   r   r   r   r   make_insecure_stub6  s
   
r   r   )T)ro   )r   )Er(   
__future__r   rH   r?   http.clientr   osr   	threadingr   Localtypingr   google.authr2   google.auth.transport.requestsgoogle.protobufr   r   r   google.auth.transport.grpcImportErrorutcnow_NOWtimezoneutcrE   r>   rZ   re   rT   rS   r   VERBOSEra   rp   __annotations__r   
expanduserr
   join_GCLOUD_CONFIG_FILE_GCLOUD_CONFIG_SECTION_GCLOUD_CONFIG_KEYr   r1   r6   r;   rC   r8   rL   rO   rY   r\   rj   rn   ru   rw   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s~   
'

#

+
 