
    BfH                        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 	 ddlZddlZn# e$ r dZY nw xY wej        j        Zej        j        Z ej        dd	d	ej        j        
          ZdZdZdZdZ  ej!        dej"                  Z#ee$df         e%d<   	 ej&        '                    d          Z(n# e$ r dZ(Y nw xY wej&        )                    ddd          Z*dZ+dZ, G d de          Z-d Z.d3dZ/d Z0d Z1d Z2d Z3d Z4d  Z5d! Z6d" Z7d4d$Z8d5d&Z9d' Z:d( Z;d) Z<d* Z=d+ Z>d, Z?d- Z@d. ZAd6d0ZBd6d1ZCd3d2ZDdS )7z^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                   J     e Zd ZdZ fdZd Zd Zd Zed             Z	 x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                 d    t          t          |                                            g | _        d S N)superr   __init___stack)self	__class__s    m/home/panchajanya/Development/work/volatility3/lib/python3.11/site-packages/google/cloud/_helpers/__init__.pyr   z_LocalStack.__init__S   s*    k4  ))+++    c                 D    t          t          | j                            S )z Iterate the stack in LIFO order.)iterreversedr   r   s    r   __iter__z_LocalStack.__iter__W   s    HT[))***r   c                 :    | j                             |           dS )zPush a resource onto our stack.N)r   append)r   resources     r   pushz_LocalStack.push[   s    8$$$$$r   c                 4    | 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    s    r   r'   z_LocalStack.pop_   s     {   r   c                 .    | 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    s    r   topz_LocalStack.toph   s$     ; 	#;r?"	# 	#r   )__name__
__module____qualname____doc__r   r!   r%   r'   propertyr*   __classcell__)r   s   @r   r   r   L   s             + + +% % %! ! ! # # X# # # # #r   r   c                     t          |t          t          f          st          d| d|          t          |          S )a  Ensures an input is a tuple or list.

    This effectively reduces the iterable types allowed to a very short
    allowlist: 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 z! to be a tuple or list. Received )
isinstancetuplelist	TypeError)arg_nametuple_or_lists     r   _ensure_tuple_or_listr8   s   sN      meT]33 
i%XX}}6
 
 	
 r   c                 L    | !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.
    )googleauthdefault)r   _s     r   _determine_default_projectr>      s%     [((**
7Nr   c                 *    t          |           }|dz  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micross     r   _millisrD      s     )..FT>r   c                 <    t           t          j        |           z   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values    r   _datetime_from_microsecondsrL      s     H&E:::::r   c                     | j         s|                     t                    } |                     t                    } t	          t          j        |                                           dz            | j        z   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microsecondrJ   s    r   rA   rA      sc     < *S))S!!Exu0011C7885;LLLr   c                 (    | 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)rD   rJ   s    r   _millis_from_datetimerW      s     u~~ r   c                 f    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)rH   strptimedaterJ   s    r   _date_from_iso8601_dater[      s)     %%eZ88==???r   c                    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formatrH   rY   time)rK   fmts     r   _time_from_iso8601_time_naiverf      st     5zzQ#	Ur		 299%@@AAA%%eS1166888r   c                 ~    t           j                             | t                                        t                    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	   )rH   rY   _RFC3339_MICROSrN   rO   )dt_strs    r   _rfc3339_to_datetimerj      s.     %%fo>>FFcFRRRr   c                    t                               |           }|t          d| dt           j                  t          j                            |                    d          t                    }|                    d          }|d}n,dt          |          z
  }t          |          d|z  z  }|d	z  }|
                    |t          
          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: z, does not match pattern: no_fractionnanosr   	   
   r@   )rU   r
   )_RFC3339_NANOSmatchrb   patternrH   rY   group_RFC3339_NO_FRACTIONr_   rQ   rN   rO   )ri   
with_nanosbare_secondsfractionrC   scalerm   s          r   _rfc3339_nanos_to_datetimery      s       %%f--Jjvv~--/
 
 	
 $--'')= L ((HCMM!HU+$F3???r   Tc                     |s2| j         +|                     d          |                                 z
  } |                     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
   rN   	utcoffsetstrftimerh   )rK   ignore_zones     r   _datetime_to_rfc3339r~   "  sG      ?5<3T**U__->->>>>/***r   asciic                     t          | t                    r|                     |          n| }t          |t                    r|S t	          | d          )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  could not be converted to bytes)r2   strencodebytesr5   )rK   encodingresults      r   	_to_bytesr   6  sV    & (2%'='=HU\\(###5F&%   IGHHHr   c                     t          | t                    r|                     d          n| }t          |t                    r|S t	          | d          )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" could not be converted to unicode)r2   r   decoder   rb   )rK   r   s     r   _bytes_to_unicoder   P  sV     '1&>&>IU\\'"""EF&# L555JKKKr   c                      |             }|                     |          s2t          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 {})Unpackr5   rc   r   r+   )pb_typeany_pbmsgs      r   _from_any_pbr   c  s]     '))C== 
(// )7+; 
 
 	
 Jr   c                 X    t           t          j        | j        | j        dz            z   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.
         @@secondsrF   )rG   rH   rI   r   rm   )timestamp_pbs    r   _pb_timestamp_to_datetimer   |  s5     H&$L4F4O    r   c                 >    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   r~   )r   	timestamps     r   _pb_timestamp_to_rfc3339r     s     *,77I	***r   c                 |    t          |           }t          |d          \  }}|dz  }t          j        ||          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 r@   )r   rm   )rA   divmodr   	Timestamp)rB   ms_valuer   rC   rm   s        r   _datetime_to_pb_timestampr     sC     +400HXu--OGVUNE"7%@@@@r   c                 V    t          j                    }|                    |            |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_pbs     r   _timedelta_to_duration_pbr     s,     '))Km,,,r   c                 H    t          j        | j        | j        dz            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   )rH   rI   r   rm   )r   s    r   _duration_pb_to_timedeltar     s.     #;3Dv3M   r   c                 H   t          |t                    rt          j        |          }|                    |           }|st          d| d|j        d          |1|                    d          }||k    rt          d|d|d          |                    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 "z"" did not match expected pattern ""Nr   zProject from client (z*) should agree with project from resource(z).name)r2   r   recompilerq   rb   rr   rs   )pathr   templaterq   found_projects        r   _name_from_project_pathr     s    , (C   (:h''NN4  E 
j?CttXEUEUEUV
 
 	
 I..G##*07H  
 ;;vr    c                     d|t           j        j        fz  }t          j        j        j                                        }d|f}|f|z   }t          j        j        j        	                    | |||          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_PORTr:   r;   	transportrequestsRequestgrpcsecure_authorized_channel)credentials
user_agenthostextra_optionstargethttp_requestuser_agent_optionr   s           r   make_secure_channelr     sx    , dk455F;(199;;L2J? "]2G; %??\67 @   r   c                 >    t          | |||          } ||          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   channels         r   make_secure_stubr     s3    2 "Z]  G :gr   c                 X    ||}nd||fz  }t          j        |          } | |          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   s        r   make_insecure_stubr   6  s@    $ | D$<'#F++G:gr   r   )T)r   )r   )Er.   
__future__r   rR   rH   http.clientr   osr   	threadingr   Localtypingr   google.authr:   google.auth.transport.requestsgoogle.protobufr   r   r   google.auth.transport.grpcImportErrorutcnow_NOWtimezoneutcrO   rG   rh   rt   ra   r`   r   VERBOSErp   r   __annotations__r   
expanduserr   join_GCLOUD_CONFIG_FILE_GCLOUD_CONFIG_SECTION_GCLOUD_CONFIG_KEYr   r8   r>   rD   rL   rA   rW   r[   rf   rj   ry   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s    
 ' & & & & &       				 				 $ $ $ $ $ $           % % % % ( ( ( ( ( ( ) ) ) ) ) )KKK%%%%%   DDD 		4Ah.?.C	D	D	D)* " " 	 J  #t)   ##C((JJ   JJJgll8-=?OPP   $# $# $# $# $#% $# $# $#N  0   "
 
 
	; 	; 	;M M M"
 
 

@ 
@ 
@9 9 9&	S 	S 	S @  @  @F+ + + +(I I I I4L L L&  2  
+ 
+ 
+A A A  &  &( ( (V   @   >     s#   A AA7C CC