o
                        @   sL  d Z ddlZddlZddlZddlmZ g dZejZG dd deZG dd deZ	G d	d
 d
e	Z
G dd de	ZG dd de	ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZeg dZeg dZedgZdZdZdZd ZG d!d" d"eZG d#d$ d$eZG d%d& d&eeeZ G d'd( d(e Z!G d)d* d*eZ"G d+d, d,ee"eZ#G d-d. d.e$Z%G d/d0 d0eZ&G d1d2 d2ee&eZ'G d3d4 d4e'Z(G d5d6 d6e'Z)G d7d8 d8e'Z*G d9d: d:e'Z+G d;d< d<e'Z,G d=d> d>e'Z-G d?d@ d@e'Z.e/dAde0fdBdCZ1dS )Da  Stand-alone implementation of in memory protocol messages.

Public Classes:
  Enum: Represents an enumerated type.
  Variant: Hint for wire format to determine how to serialize.
  Message: Base class for user defined messages.
  IntegerField: Field for integer values.
  FloatField: Field for float values.
  BooleanField: Field for boolean values.
  BytesField: Field for binary string values.
  StringField: Field for UTF-8 string values.
  MessageField: Field for other message type values.
  EnumField: Field for enumerated type values.

Public Exceptions (indentation indications class hierarchy):
  EnumDefinitionError: Raised when enumeration is incorrectly defined.
  FieldDefinitionError: Raised when field is incorrectly defined.
    InvalidVariantError: Raised when variant is not compatible with field type.
    InvalidDefaultError: Raised when default is not compatiable with field.
    InvalidNumberError: Raised when field number is out of range or reserved.
  MessageDefinitionError: Raised when message is incorrectly defined.
    DuplicateNumberError: Raised when field has duplicate number with another.
  ValidationError: Raised when a message or field is not valid.
  DefinitionNotFoundError: Raised when definition not found.
    N)util)MAX_ENUM_VALUEMAX_FIELD_NUMBERFIRST_RESERVED_FIELD_NUMBERLAST_RESERVED_FIELD_NUMBEREnumField	FieldListVariantMessageIntegerField
FloatFieldBooleanField
BytesFieldStringFieldMessageField	EnumFieldfind_definitionErrorDecodeErrorEncodeErrorEnumDefinitionErrorFieldDefinitionErrorInvalidVariantErrorInvalidDefaultErrorInvalidNumberErrorMessageDefinitionErrorDuplicateNumberErrorValidationErrorDefinitionNotFoundErrorc                   @      e Zd ZdZdS )r   zEnumeration definition error.N__name__
__module____qualname____doc__ r&   r&   L/tmp/google-cloud-sdk/lib/third_party/apitools/base/protorpclite/messages.pyr   _       r   c                   @   r    )r   zField definition error.Nr!   r&   r&   r&   r'   r   c   r(   r   c                   @   r    )r   z"Invalid variant provided to field.Nr!   r&   r&   r&   r'   r   g   r(   r   c                   @   r    )r   z"Invalid default provided to field.Nr!   r&   r&   r&   r'   r   k   r(   r   c                   @   r    )r   z!Invalid number provided to field.Nr!   r&   r&   r&   r'   r   o   r(   r   c                   @   r    )r   zMessage definition error.Nr!   r&   r&   r&   r'   r   s   r(   r   c                   @   r    )r   z#Duplicate number assigned to field.Nr!   r&   r&   r&   r'   r   w   r(   r   c                   @   r    )r   z$Raised when definition is not found.Nr!   r&   r&   r&   r'   r   {   r(   r   c                   @   r    )r   z/Error found decoding message from encoded form.Nr!   r&   r&   r&   r'   r      r(   r   c                   @   r    )r   z"Error found when encoding message.Nr!   r&   r&   r&   r'   r      r(   r   c                   @   s   e Zd ZdZdd ZdS )r   z Invalid value for message error.c                 C   s
   t | S )z6Prints string with field name if present on exception.)r   __str__selfr&   r&   r'   r)         
zValidationError.__str__N)r"   r#   r$   r%   r)   r&   r&   r&   r'   r      s    r   )r#   r%   r$   __static_attributes____firstlineno__)name_message_definition_MessageField__type_EnumField__type_EnumField__resolved_defaultr0   ii8J  iN  c                   @   sL   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd ZdS )_DefinitionClassau  Base meta-class used for definition meta-classes.

    The Enum and Message definition classes share some basic functionality.
    Both of these classes may be contained by a Message definition.  After
    initialization, neither class may have attributes changed
    except for the protected _message_definition attribute, and that attribute
    may change only once.
    Fc                 C   s*   t | ||| | jtfkrd| _dS dS )zConstructor.TN)type__init__	__bases__object_DefinitionClass__initializedclsr/   basesdctr&   r&   r'   r6      s   
z_DefinitionClass.__init__c                 C       z|   W S  ty   Y dS w )zGet outer Message definition that contains this definition.

        Returns:
          Containing Message definition if definition is contained within one,
          else None.
        Nr0   AttributeErrorr;   r&   r&   r'   message_definition   s
   
z#_DefinitionClass.message_definitionc                 C   s,   | j r|tvrtd| t| || dS )a  Overridden to avoid setting variables after init.

        Setting attributes on a class must work during the period of
        initialization to set the enumation value class variables and
        build the name/number maps. Once __init__ has set the
        __initialized flag to True prohibits setting any more values
        on the class. The class is in effect frozen.

        Args:
          name: Name of value to set.
          value: Value to set.

        zMay not change values: %sN)r9   _POST_INIT_ATTRIBUTE_NAMESr@   r5   __setattr__)r;   r/   valuer&   r&   r'   rD      s   z_DefinitionClass.__setattr__c                 C      t d)zAOverridden so that cannot delete varaibles on definition classes.z-May not delete attributes on definition class	TypeErrorr;   r/   r&   r&   r'   __delattr__   s   z_DefinitionClass.__delattr__c                 C   s*   |   }|du rt| jS d|| jf S )a  Helper method for creating definition name.

        Names will be generated to include the classes package name,
        scope (if the class is nested in another definition) and class
        name.

        By default, the package name for a definition is derived from
        its module name. However, this value can be overriden by
        placing a 'package' attribute in the module that contains the
        definition class. For example:

          package = 'some.alternate.package'

          class MyMessage(Message):
            ...

          >>> MyMessage.definition_name()
          some.alternate.package.MyMessage

        Returns:
          Dot-separated fully qualified name of definition.

        N%s.%s)outer_definition_namesix	text_typer"   )r;   rL   r&   r&   r'   definition_name   s   z _DefinitionClass.definition_namec                 C       |   }|st| jS | S )zHelper method for creating outer definition name.

        Returns:
          If definition is nested, will return the outer definitions
          name, else the package name.

        )rB   r   get_package_for_moduler#   rO   r;   outer_definitionr&   r&   r'   rL      s   z&_DefinitionClass.outer_definition_namec                 C   rP   )zHelper method for creating creating the package of a definition.

        Returns:
          Name of package that definition belongs to.
        )rB   r   rQ   r#   definition_packagerR   r&   r&   r'   rT     s   z#_DefinitionClass.definition_packageN)r"   r#   r$   r%   r9   r6   rB   rD   rJ   rO   rL   rT   r&   r&   r&   r'   r4      s    	r4   c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )
_EnumClassaF  Meta-class used for defining the Enum base class.

    Meta-class enables very specific behavior for any defined Enum
    class.  All attributes defined on an Enum sub-class must be integers.
    Each attribute defined on an Enum sub-class is translated
    into an instance of that sub-class, with the name of the attribute
    as its name, and the number provided as its value.  It also ensures
    that only one level of Enum class hierarchy is possible.  In other
    words it is not possible to delcare sub-classes of sub-classes of
    Enum.

    This class also defines some functions in order to restrict the
    behavior of the Enum class and its sub-classes.  It is not possible
    to change the behavior of the Enum class in later classes since
    any new classes may be defined with only integer values, and no methods.
    c                 C   s  |t fks|tfkstd| i | _i | _|t fkr| D ]`\}}|tv r(qt|tj	s6td||f |dk rBtd||f |t
krOtdt
||f || jv ratd||| j| jf t | }| ||| || j|j< || j|j< t| || qt| ||| d S )Nz'Enum type %s may only inherit from Enumz:May only use integers in Enum definitions.  Found: %s = %sr   z2Must use non-negative enum values.  Found: %s = %dz;Must use enum values less than or equal %d.  Found: %s = %dz(Value for %s = %d is already defined: %s)r8   r   r   _EnumClass__by_number_EnumClass__by_nameitems_RESERVED_ATTRIBUTE_NAMES
isinstancerM   integer_typesr   r/   __new__r6   numbersetattrr4   )r;   r/   r<   r=   	attributerE   instancer&   r&   r'   r6   +  sP   


z_EnumClass.__init__c                 C      t | j S )zIterate over all values of enum.

        Yields:
          Enumeration instances of the Enum class in arbitrary order.
        )iterrV   valuesrA   r&   r&   r'   __iter__`  s   z_EnumClass.__iter__c                 C   
   | j  S )zyGet all names for Enum.

        Returns:
          An iterator for names of the enumeration in arbitrary order.
        )rW   keysrA   r&   r&   r'   namesh     
z_EnumClass.namesc                 C   re   )zGet all numbers for Enum.

        Returns:
          An iterator for all numbers of the enumeration in arbitrary order.
        )rV   rf   rA   r&   r&   r'   numbersp  rh   z_EnumClass.numbersc                 C   
   | j | S )zLook up Enum by name.

        Args:
          name: Name of enum to find.

        Returns:
          Enum sub-class instance of that value.
        )rW   rI   r&   r&   r'   lookup_by_namex     
	z_EnumClass.lookup_by_namec                 C   rj   )zLook up Enum by number.

        Args:
          number: Number of enum to find.

        Returns:
          Enum sub-class instance of that value.
        )rV   r;   r]   r&   r&   r'   lookup_by_number  rl   z_EnumClass.lookup_by_numberc                 C   
   t | jS N)lenrW   rA   r&   r&   r'   __len__  s   
z_EnumClass.__len__N)r"   r#   r$   r%   r6   rd   rg   ri   rk   rn   rr   r&   r&   r&   r'   rU     s    5rU   c                   @   s   e Zd ZdZedZdd Zd&ddZdd	 Zd
d Z	dd Z
dd Zdd Zdd Z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ed$d% ZdS )'r   z$Base class for all enumerated types.r/   r]   c                 C   sx   t || r|S t |tjrz| |W S  ty   Y nw t |tjr3z| |W S  ty2   Y nw td|| jf )aG  Acts as look-up routine after class is initialized.

        The purpose of overriding __new__ is to provide a way to treat
        Enum subclasses as casting types, similar to how the int type
        functions.  A program can pass a string or an integer and this
        method with "convert" that value in to an appropriate Enum instance.

        Args:
          index: Name or number to look up.  During initialization
            this is always the name of the new enum value.

        Raises:
          TypeError: When an inappropriate index value is passed provided.
        zNo such value for %s in Enum %s)	rZ   rM   r[   rn   KeyErrorstring_typesrk   rH   r"   )r;   indexr&   r&   r'   r\     s"   
zEnum.__new__Nc                 C   s2   t t| dr	dS t| d| t| d| dS )zInitialize new Enum instance.

        Since this should only be called during class initialization any
        calls that happen after the class is frozen raises an exception.
        r9   Nr/   r]   )getattrr5   r8   rD   )r+   r/   r]   r&   r&   r'   r6     s   	zEnum.__init__c                 C   rF   )NzMay not change enum valuesrG   r+   r/   rE   r&   r&   r'   rD     s   zEnum.__setattr__c                 C      | j S rp   )r/   r*   r&   r&   r'   r)        zEnum.__str__c                 C   ry   rp   r]   r*   r&   r&   r'   __int__  rz   zEnum.__int__c                 C   s   dt | j| j| jf S )Nz
%s(%s, %d))r5   r"   r/   r]   r*   r&   r&   r'   __repr__  s   zEnum.__repr__c                 C   s   | j | jffS )zEnable pickling.

        Returns:
          A 2-tuple containing the class and __new__ args to be used
          for restoring a pickled instance.

        )	__class__r]   r*   r&   r&   r'   
__reduce__     zEnum.__reduce__c                 C   s    t |t| rt| j|jS tS zOrder is by number.)rZ   r5   cmpr]   NotImplementedr+   otherr&   r&   r'   __cmp__  s   zEnum.__cmp__c                 C   s   t |t| r| j|jk S tS r   rZ   r5   r]   r   r   r&   r&   r'   __lt__     zEnum.__lt__c                 C   s   t |t| r| j|jkS tS r   r   r   r&   r&   r'   __le__  r   zEnum.__le__c                 C   s   t |t| r| j|jkS tS r   r   r   r&   r&   r'   __eq__  r   zEnum.__eq__c                 C   s   t |t| r| j|jkS tS r   r   r   r&   r&   r'   __ne__  r   zEnum.__ne__c                 C   s   t |t| r| j|jkS tS r   r   r   r&   r&   r'   __ge__  r   zEnum.__ge__c                 C   s   t |t| r| j|jkS tS r   r   r   r&   r&   r'   __gt__  r   zEnum.__gt__c                 C   ro   )zHash by number.)hashr]   r*   r&   r&   r'   __hash__	  r,   zEnum.__hash__c                 C   s   t dd t| D S )zMake dictionary version of enumerated class.

        Dictionary created this way can be used with def_num.

        Returns:
          A dict (name) -> number
        c                 s   s    | ]	}|j |jfV  qd S rp   rs   ).0itemr&   r&   r'   	<genexpr>  s    zEnum.to_dict.<locals>.<genexpr>)dictrb   rA   r&   r&   r'   to_dict  s   	zEnum.to_dictc                 C   s   t |tf| S )zDefine enum class from dictionary.

        Args:
          dct: Dictionary of enumerated values for type.
          name: Name of enum.
        )r5   r   )r=   r/   r&   r&   r'   def_enum  r   zEnum.def_enumrp   )r"   r#   r$   r%   set	__slots__r\   r6   rD   r)   r|   r}   r   r   r   r   r   r   r   r   r   classmethodr   staticmethodr   r&   r&   r&   r'   r     s,    
$


r   c                   @   sD   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdS )r
   a(  Wire format variant.

    Used by the 'protobuf' wire format to determine how to transmit
    a single piece of data.  May be used by other formats.

    See: http://code.google.com/apis/protocolbuffers/docs/encoding.html

    Values:
      DOUBLE: 64-bit floating point number.
      FLOAT: 32-bit floating point number.
      INT64: 64-bit signed integer.
      UINT64: 64-bit unsigned integer.
      INT32: 32-bit signed integer.
      BOOL: Boolean value (True or False).
      STRING: String of UTF-8 encoded text.
      MESSAGE: Embedded message as byte string.
      BYTES: String of 8-bit bytes.
      UINT32: 32-bit unsigned integer.
      ENUM: Enum value as integer.
      SINT32: 32-bit signed integer.  Uses "zig-zag" encoding.
      SINT64: 64-bit signed integer.  Uses "zig-zag" encoding.
                      	                     N)r"   r#   r$   r%   DOUBLEFLOATINT64UINT64INT32BOOLSTRINGMESSAGEBYTESUINT32ENUMSINT32SINT64r&   r&   r&   r'   r
   %  s    r
   c                   @   s    e Zd ZdZdd Zdd ZdS )_MessageClassa  Meta-class used for defining the Message base class.

    For more details about Message classes, see the Message class docstring.
    Information contained there may help understanding this class.

    Meta-class enables very specific behavior for any defined Message
    class. All attributes defined on an Message sub-class must be
    field instances, Enum class definitions or other Message class
    definitions. Each field attribute defined on an Message sub-class
    is added to the set of field definitions and the attribute is
    translated in to a slot. It also ensures that only one level of
    Message class hierarchy is possible. In other words it is not
    possible to declare sub-classes of sub-classes of Message.

    This class also defines some functions in order to restrict the
    behavior of the Message class and its sub-classes. It is not
    possible to change the behavior of the Message class in later
    classes since any new classes may be defined with only field,
    Enums and Messages, and no methods.

    c                 C   s.  i }i }i }|t fkr|tfkrtdg }g }| D ]Z\}	}
|	tv r%qt|
tr5t|
tr5|	|	 qt|
trIt|
trI|
turI|	|	 qt|
t
u sTt|
t
s\td|	|
f |
j|v rjtd|
j|f |	|
_|
||	< |
||
j< q|rt||d< |rt||d< ||d< ||d< t| |||S )zCreate new Message class instance.

        The __new__ method of the _MessageClass type is overridden so as to
        allow the translation of Field instances to slots.
        z+Message types may only inherit from Messagez;May only use fields in message definitions.  Found: %s = %sz2Field with number %d declared more than once in %s	__enums____messages___Message__by_number_Message__by_name)r8   r   r   rX   rY   rZ   r5   
issubclassr   appendr   r]   r   r/   sortedr4   r\   )r;   r/   r<   r=   	by_numberby_namevariant_mapenumsmessageskeyfieldr&   r&   r'   r\   c  sX   





z_MessageClass.__new__c                 C   sd   |t fkr(| D ]}t|tr|turt| |_q	|  D ]}t| |_qt	| ||| dS )z7Initializer required to assign references to new class.N)
r8   rc   rZ   r4   r   weakrefrefr0   
all_fieldsr6   )r;   r/   r<   r=   vr   r&   r&   r'   r6     s   
z_MessageClass.__init__N)r"   r#   r$   r%   r\   r6   r&   r&   r&   r'   r   K  s    Dr   c                   @   s   e Zd ZdZdd Zdd Zdd Zedd	 Zed
d Z	edd Z
dd Zdd Zdd Z		d!ddZdd Zdd Zdd Zdd Zdd  ZdS )"r   a	  Base class for user defined message objects.

    Used to define messages for efficient transmission across network or
    process space.  Messages are defined using the field classes (IntegerField,
    FloatField, EnumField, etc.).

    Messages are more restricted than normal classes in that they may
    only contain field attributes and other Message and Enum
    definitions. These restrictions are in place because the structure
    of the Message class is intentended to itself be transmitted
    across network or process space and used directly by clients or
    even other servers. As such methods and non-field attributes could
    not be transmitted with the structural information causing
    discrepancies between different languages and implementations.

    Initialization and validation:

      A Message object is considered to be initialized if it has all required
      fields and any nested messages are also initialized.

      Calling 'check_initialized' will raise a ValidationException if it is not
      initialized; 'is_initialized' returns a boolean value indicating if it is
      valid.

      Validation automatically occurs when Message objects are created
      and populated.  Validation that a given value will be compatible with
      a field that it is assigned to can be done through the Field instances
      validate() method.  The validate method used on a message will check that
      all values of a message and its sub-messages are valid.  Assingning an
      invalid value to a field will raise a ValidationException.

    Example:

      # Trade type.
      class TradeType(Enum):
        BUY = 1
        SELL = 2
        SHORT = 3
        CALL = 4

      class Lot(Message):
        price = IntegerField(1, required=True)
        quantity = IntegerField(2, required=True)

      class Order(Message):
        symbol = StringField(1, required=True)
        total_quantity = IntegerField(2, required=True)
        trade_type = EnumField(TradeType, 3, required=True)
        lots = MessageField(Lot, 4, repeated=True)
        limit = IntegerField(5)

      order = Order(symbol='GOOG',
                    total_quantity=10,
                    trade_type=TradeType.BUY)

      lot1 = Lot(price=304,
                 quantity=7)

      lot2 = Lot(price = 305,
                 quantity=3)

      order.lots = [lot1, lot2]

      # Now object is initialized!
      order.check_initialized()

    c                 K   sj   i | _ i | _t }| D ]\}}t| || || q|  D ]}|jr2|j|vr2t| |jg  q!dS )a.  Initialize internal messages state.

        Args:
          A message can be initialized via the constructor by passing
          in keyword arguments corresponding to fields. For example:

            class Date(Message):
              day = IntegerField(1)
              month = IntegerField(2)
              year = IntegerField(3)

          Invoking:

            date = Date(day=6, month=6, year=1911)

          is the same as doing:

            date = Date()
            date.day = 6
            date.month = 6
            date.year = 1911

        N)	_Message__tags_Message__unrecognized_fieldsr   rX   r^   addr   repeatedr/   )r+   kwargsassignedr/   rE   r   r&   r&   r'   r6     s   zMessage.__init__c                 C   s   | j  D ]\\}}t| |}|du r!|jr tdt| j|f qz(t|trHt	|j
trH|jr?|D ]}||}|  q2n	||}|  W q tya } zt|ds\t| j|_ d}~ww dS )zCheck class for initialization status.

        Check that all required fields are initialized

        Raises:
          ValidationError: If message is not initialized.
        Nz'Message %s is missing required field %smessage_name)r   rX   rw   requiredr   r5   r"   rZ   r   r   message_typer   r   value_to_messagecheck_initializedhasattrr   )r+   r/   r   rE   r   item_message_valuemessage_valueerrr&   r&   r'   r     s>   





zMessage.check_initializedc                 C   s$   z|    W dS  ty   Y dS w )zeGet initialization status.

        Returns:
          True if message is valid, else False.
        FT)r   r   r*   r&   r&   r'   is_initialized?  s   
zMessage.is_initializedc                 C   re   )zGet all field definition objects.

        Ordering is arbitrary.

        Returns:
          Iterator over all values in arbitrary order.
        )r   rc   rA   r&   r&   r'   r   L  rl   zMessage.all_fieldsc                 C   rj   )zGet field by name.

        Returns:
          Field object associated with name.

        Raises:
          KeyError if no field found by that name.
        )r   rI   r&   r&   r'   field_by_nameW     

zMessage.field_by_namec                 C   rj   )zGet field by number.

        Returns:
          Field object associated with number.

        Raises:
          KeyError if no field found by that number.
        )r   rm   r&   r&   r'   field_by_numberc  r   zMessage.field_by_numberc                 C   sF   t | }z||}W n ty   td|j|f w | j|jS )a8  Get the assigned value of an attribute.

        Get the underlying value of an attribute. If value has not
        been set, will not return the default for the field.

        Args:
          name: Name of attribute to get.

        Returns:
          Value of attribute, None if it has not been set.

        Message %s has no field %s)r5   r   rt   r@   r"   r   getr]   r+   r/   r   r   r&   r&   r'   get_assigned_valueo  s   zMessage.get_assigned_valuec                 C   sv   t | }z||}W n ty"   ||jvr td|j|f Y nw |jr1t|g | j|j	< dS | j
|j	d dS )zReset assigned value for field.

        Resetting a field will return it to its default value or None.

        Args:
          name: Name of field to reset.
        r   N)r5   r   rt   r   r@   r"   r   r	   r   r]   popr   r&   r&   r'   reset  s   
zMessage.resetc                 C   ra   )z9Get the names of all unrecognized fields in this message.)listr   rf   r*   r&   r&   r'   all_unrecognized_fields  s   zMessage.all_unrecognized_fieldsNc                 C   s   | j |||f\}}||fS )a  Get the value and variant of an unknown field in this message.

        Args:
          key: The name or number of the field to retrieve.
          value_default: Value to be returned if the key isn't found.
          variant_default: Value to be returned as variant if the key isn't
            found.

        Returns:
          (value, variant), where value and variant are whatever was passed
          to set_unrecognized_field.
        )r   r   )r+   r   value_defaultvariant_defaultrE   variantr&   r&   r'   get_unrecognized_field_info  s   

z#Message.get_unrecognized_field_infoc                 C   s(   t |tstd| ||f| j|< dS )a|  Set an unrecognized field, used when decoding a message.

        Args:
          key: The name or number used to refer to this unknown value.
          value: The value of the field.
          variant: Type information needed to interpret the value or re-encode
            it.

        Raises:
          TypeError: If the variant is not an instance of messages.Variant.
        zVariant type %s is not valid.N)rZ   r
   rH   r   )r+   r   rE   r   r&   r&   r'   set_unrecognized_field  s   
zMessage.set_unrecognized_fieldc                 C   s<   || j v s
|drt| || dS td|t| jf )a\  Change set behavior for messages.

        Messages may only be assigned values that are fields.

        Does not try to validate field when set.

        Args:
          name: Name of field to assign to.
          value: Value to assign to field.

        Raises:
          AttributeError when trying to assign value that is not a field.
        
_Message__z/May not assign arbitrary value %s to message %sN)r   
startswithr8   rD   r@   r5   r"   rx   r&   r&   r'   rD     s
   zMessage.__setattr__c                 C   sl   dt | jg}t|  dd dD ]}|j}| |j}|dur+|d|t|f  q|d d|S )	a\  Make string representation of message.

        Example:

          class MyMessage(messages.Message):
            integer_value = messages.IntegerField(1)
            string_value = messages.StringField(2)

          my_message = MyMessage()
          my_message.integer_value = 42
          my_message.string_value = u'A string'

          print my_message
          >>> <MyMessage
          ...  integer_value: 42
          ...  string_value: u'A string'>

        Returns:
          String representation of message, including the values
          of all fields and repr of all sub-messages.
        <c                 S   ry   rp   r{   )fr&   r&   r'   <lambda>  s    z"Message.__repr__.<locals>.<lambda>)r   Nz
 %s: %s> )	r5   r"   r   r   r/   r   r   reprjoin)r+   bodyr   r_   rE   r&   r&   r'   r}     s   


zMessage.__repr__c                 C   s,   | |u rdS t | t |urdS | j|jkS )a  Equality operator.

        Does field by field comparison with other message.  For
        equality, must be same type and values of all fields must be
        equal.

        Messages not required to be initialized for comparison.

        Does not attempt to determine equality for values that have
        default values that are not set.  In other words:

          class HasDefault(Message):

            attr1 = StringField(1, default='default value')

          message1 = HasDefault()
          message2 = HasDefault()
          message2.attr1 = 'default value'

          message1 != message2

        Does not compare unknown values.

        Args:
          other: Other message to compare with.
        TF)r5   r   r   r&   r&   r'   r     s
   zMessage.__eq__c                 C   s   |  | S )af  Not equals operator.

        Does field by field comparison with other message.  For
        non-equality, must be different type or any value of a field must be
        non-equal to the same field in the other instance.

        Messages not required to be initialized for comparison.

        Args:
          other: Other message to compare with.
        )r   r   r&   r&   r'   r     s   zMessage.__ne__)NN)r"   r#   r$   r%   r6   r   r   r   r   r   r   r   r   r   r   r   rD   r}   r   r   r&   r&   r&   r'   r     s,    D& 




 %r   c                   @   s\   e Zd Z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 )r	   a  List implementation that validates field values.

    This list implementation overrides all methods that add values in
    to a list in order to validate those new elements. Attempting to
    add or set list values that are not of the correct type will raise
    ValidationError.

    c                 C   s0   |j std|| _| j| t| | dS )zConstructor.

        Args:
          field_instance: Instance of field that validates the list.
          sequence: List or tuple to construct list from.
        z)FieldList may only accept repeated fieldsN)r   r   _FieldList__fieldvalidater   r6   )r+   field_instancesequencer&   r&   r'   r6   0  s   zFieldList.__init__c                 C   s,   | j  }|du r| j ddfS d|| j jfS )a  Enable pickling.

        The assigned field instance can't be pickled if it belongs to
        a Message definition (message_definition uses a weakref), so
        the Message class and field number are returned in that case.

        Returns:
          A 3-tuple containing:
            - The field instance, or None if it belongs to a Message class.
            - The Message class that the field instance belongs to, or None.
            - The field instance number of the Message class it belongs to, or
                None.

        N)r   rB   r]   )r+   message_classr&   r&   r'   __getstate__>  s   
zFieldList.__getstate__c                 C   s,   |\}}}|du r| || _dS || _dS )aO  Enable unpickling.

        Args:
          state: A 3-tuple containing:
            - The field instance, or None if it belongs to a Message class.
            - The Message class that the field instance belongs to, or None.
            - The field instance number of the Message class it belongs to, or
                None.
        N)r   r   )r+   stater   r   r]   r&   r&   r'   __setstate__R  s   


zFieldList.__setstate__c                 C   ry   )zField that validates list.)r   r*   r&   r&   r'   r   b     zFieldList.fieldc                 C   s    | j | t| ||| dS )z"Validate slice assignment to list.N)r   r   r   __setslice__)r+   ijr   r&   r&   r'   r   g  s   zFieldList.__setslice__c                 C   s6   t |tr| j| n| j| t| || dS )z!Validate item assignment to list.N)rZ   slicer   r   validate_elementr   __setitem__r+   rv   rE   r&   r&   r'   r   l  s   
zFieldList.__setitem__c                 C   $   t | ddr| j| t| |S )z Validate item appending to list.r   N)rw   r   r   r   r   r+   rE   r&   r&   r'   r   t     zFieldList.appendc                 C   r  )zValidate extension of list.r   N)rw   r   r   r   extend)r+   r   r&   r&   r'   r  z  r  zFieldList.extendc                 C   s   | j | t| ||S )z Validate item insertion to list.)r   r   r   insertr  r&   r&   r'   r    s   zFieldList.insertN)r"   r#   r$   r%   r6   r   r   propertyr   r   r   r   r  r  r&   r&   r&   r'   r	   &  s    	
r	   c                   @   s   e Zd Zdd ZdS )
_FieldMetac                    s:   t  d fdd|dg D  t ||| d S )N_Field__variant_to_typec                 3   s    | ]}| fV  qd S rp   r&   )r   r   rA   r&   r'   r     s    
z&_FieldMeta.__init__.<locals>.<genexpr>VARIANTS)rw   updater   r5   r6   r:   r&   rA   r'   r6     s   
z_FieldMeta.__init__N)r"   r#   r$   r6   r&   r&   r&   r'   r    s    r  c                   @   s   e Zd ZdZdZi Zed				dddZdd Z	d	d
 Z
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edd ZdS )r   zDefinition for message field.Fr   Nc                 C   sN  t |trd|  krtksn td|tf t|  kr"tkr-n n	td|ttf |r5|r5td|du r<| j}|rF|durFtd|| jvrZt	d|t
| jt| jf || _|| _|| _|| _|durz| | W n- ty } z!z| j}W n ty   td| jj||f w td	|||f d}~ww || _d
| _dS )a  Constructor.

        The required and repeated parameters are mutually exclusive.
        Setting both to True will raise a FieldDefinitionError.

        Sub-class Attributes:
          Each sub-class of Field must define the following:
            VARIANTS: Set of variant types accepted by that field.
            DEFAULT_VARIANT: Default variant type if not specified in
              constructor.

        Args:
          number: Number of field.  Must be unique per message class.
          required: Whether or not field is required.  Mutually exclusive with
            'repeated'.
          repeated: Whether or not field is repeated.  Mutually exclusive with
            'required'.
          variant: Wire-format variant hint.
          default: Default value for field if not found in stream.

        Raises:
          InvalidVariantError when invalid variant for field is provided.
          InvalidDefaultError when invalid default for field is provided.
          FieldDefinitionError when invalid number provided or mutually
            exclusive fields are used.
          InvalidNumberError when the field number is out of range or reserved.

        r   zGInvalid number for field: %s
Number must be 1 or greater and %d or lesszATag number %d is a reserved number.
Numbers %d to %d are reservedz%Cannot set both repeated and requiredNz%Repeated fields may not have defaultsz0Invalid variant: %s
Valid variants for %s are %rz$Invalid default value for %s: %r: %sz*Invalid default value for field %s: %r: %sT)rZ   intr   r   r   r   r   DEFAULT_VARIANTr
  r   r5   r"   r   r]   r   r   r   validate_defaultr   r/   r@   r   r~   _Field__default_Field__initialized)r+   r]   r   r   r   defaultr   r/   r&   r&   r'   r6     sd    #


zField.__init__c                 C   s:   |t v rt| || dS | jst| || dS td)zSetter overidden to prevent assignment to fields after creation.

        Args:
          name: Name of attribute to set.
          value: Value to assign.
        NzField objects are read-only) _POST_INIT_FIELD_ATTRIBUTE_NAMESr8   rD   r  r@   rx   r&   r&   r'   rD     s   zField.__setattr__c                 C   s\   |du r| j rtd| j |j| jd dS | j r!t| |}n| |}||j| j< dS )Set value on message.

        Args:
          message_instance: Message instance to set value on.
          value: Value to set on message.
        Nz(May not assign None to repeated field %s)r   r   r/   r   r   r]   r	   r   r+   message_instancerE   r&   r&   r'   __set__  s   
zField.__set__c                 C   s,   |d u r| S |j | j}|d u r| jS |S rp   )r   r   r]   r  )r+   r  r   resultr&   r&   r'   __get__  s   zField.__get__c              
   C   s   t || jsKt |tjr| jtkrt|S |du r"| jr td|S z| j}W n ty=   td| j| j	j
|t|f w td| j||t|f |S )aW  Validate single element of field.

        This is different from validate in that it is used on individual
        values of repeated fields.

        Args:
          value: Value to validate.

        Returns:
          The value casted in the expected type.

        Raises:
          ValidationError if value is not expected type.
        NzRequired field is missingz+Expected type %s for %s, found %s (type %s)z1Expected type %s for field %s, found %s (type %s))rZ   r5   rM   r[   floatr   r   r/   r@   r~   r"   )r+   rE   r/   r&   r&   r'   r     s,   

zField.validate_elementc              	   C   s   | j s||S t|ttfr=g }|D ](}|du r3z| j}W n ty,   td| jj w td| |	|| q|S |dur`z| j}W n tyW   td| jj|f w td||f |S )aO  Internal validation function.

        Validate an internal value using a function to validate
        individual elements.

        Args:
          value: Value to validate.
          validate_element: Function to use to validate individual elements.

        Raises:
          ValidationError if value is not expected type.

        Nz&Repeated values for %s may not be Nonez,Repeated values for field %s may not be Nonez%s is repeated. Found: %szField %s is repeated. Found: %s)
r   rZ   r   tupler/   r@   r   r~   r"   r   )r+   rE   r   r  elementr/   r&   r&   r'   
__validateA  sD   


zField.__validatec                 C      |  || jS )zValidate value assigned to field.

        Args:
          value: Value to validate.

        Returns:
          the value in casted in the correct type.

        Raises:
          ValidationError if value is not expected type.
        )_Field__validater   r  r&   r&   r'   r   n     zField.validatec                 C   s
   |  |S )a&  Validate value as assigned to field default field.

        Some fields may allow for delayed resolution of default types
        necessary in the case of circular definition references. In
        this case, the default value might be a place holder that is
        resolved when needed after all the message classes are
        defined.

        Args:
          value: Default value to validate.

        Returns:
          the value in casted in the correct type.

        Raises:
          ValidationError if value is not expected type.

        )r   r  r&   r&   r'   validate_default_element|  s   
zField.validate_default_elementc                 C   r  )zValidate default value assigned to field.

        Args:
          value: Value to validate.

        Returns:
          the value in casted in the correct type.

        Raises:
          ValidationError if value is not expected type.
        )r  r   r  r&   r&   r'   r    r  zField.validate_defaultc                 C   r>   )zGet Message definition that contains this Field definition.

        Returns:
          Containing Message definition for Field. Will return None if
          for some reason Field is defined outside of a Message class.

        Nr?   r*   r&   r&   r'   rB     s
   
zField.message_definitionc                 C   ry   )zGet default value for field.)r  r*   r&   r&   r'   r    r   zField.defaultc                 C   rj   rp   )r	  )r;   r   r&   r&   r'   lookup_field_type_by_variant  r,   z"Field.lookup_field_type_by_variant)FFNN)r"   r#   r$   r%   r  r	  r   
positionalr6   rD   r  r  r   r  r   r   r  rB   r  r  r   r!  r&   r&   r&   r'   r     s.    T	&-
r   c                   @   s<   e Zd ZdZeejejejej	ej
ejgZejZejZdS )r   z$Field definition for integer values.N)r"   r#   r$   r%   	frozensetr
   r   r   r   r   r   r   r
  r  rM   r[   r5   r&   r&   r&   r'   r     s    	
r   c                   @   s*   e Zd ZdZeejejgZejZ	e
ZdS )r   z"Field definition for float values.N)r"   r#   r$   r%   r#  r
   r   r   r
  r  r  r5   r&   r&   r&   r'   r     s    r   c                   @   &   e Zd ZdZeejgZejZe	Z
dS )r   z$Field definition for boolean values.N)r"   r#   r$   r%   r#  r
   r   r
  r  boolr5   r&   r&   r&   r'   r     
    r   c                   @   r$  )r   z(Field definition for byte string values.N)r"   r#   r$   r%   r#  r
   r   r
  r  bytesr5   r&   r&   r&   r'   r     r&  r   c                       s8   e Zd ZdZeejgZejZe	j
Z fddZ  ZS )r   z+Field definition for unicode string values.c                    s   t |trCz	t|d W |S  tyB } z(z| j}W n ty-   td||f }Y |w td| j||f }| j|_|d}~ww t	t
| |S )zValidate StringField allowing for str and unicode.

        Raises:
          ValidationError if a str value is not UTF-8.
        zUTF-8z)Field encountered non-UTF-8 string %r: %sz,Field %s encountered non-UTF-8 string %r: %sN)rZ   r'  rM   rN   UnicodeDecodeErrorr/   r@   r   
field_namesuperr   r   )r+   rE   r   _validation_errorr~   r&   r'   r     s2   

zStringField.validate_element)r"   r#   r$   r%   r#  r
   r   r
  r  rM   rN   r5   r   __classcell__r&   r&   r-  r'   r     s    r   c                       sx   e Zd ZdZeejgZejZe	
d			d fdd	Z fddZed	d
 Zedd Zdd Zdd Z  ZS )r   a  Field definition for sub-message values.

    Message fields contain instance of other messages.  Instances stored
    on messages stored on message fields  are considered to be owned by
    the containing message instance and should not be shared between
    owning instances.

    Message fields must be defined to reference a single type of message.
    Normally message field are defined by passing the referenced message
    class in to the constructor.

    It is possible to define a message field for a type that does not
    yet exist by passing the name of the message in to the constructor
    instead of a message class. Resolution of the actual type of the
    message is deferred until it is needed, for example, during
    message verification. Names provided to the constructor must refer
    to a class within the same python module as the class that is
    using it. Names refer to messages relative to the containing
    messages scope. For example, the two fields of OuterMessage refer
    to the same message type:

      class Outer(Message):

        inner_relative = MessageField('Inner', 1)
        inner_absolute = MessageField('Outer.Inner', 2)

        class Inner(Message):
          ...

    When resolving an actual type, MessageField will traverse the
    entire scope of nested messages to match a message name. This
    makes it easy for siblings to reference siblings:

      class Outer(Message):

        class Inner(Message):

          sibling = MessageField('Sibling', 1)

        class Sibling(Message):
          ...

    r   FNc                    st   t |tjp|tuot |tot|t}|std| t |tjr)|| _d| _n|| _t	t
| j||||d dS )a  Constructor.

        Args:
          message_type: Message type for field.  Must be subclass of Message.
          number: Number of field.  Must be unique per message class.
          required: Whether or not field is required.  Mutually exclusive to
            'repeated'.
          repeated: Whether or not field is repeated.  Mutually exclusive to
            'required'.
          variant: Wire-format variant hint.

        Raises:
          FieldDefinitionError when invalid message_type is provided.
        Invalid message class: %sN)r   r   r   )rZ   rM   ru   r   r5   r   r   _MessageField__type_namer1   r*  r   r6   )r+   r   r]   r   r   r   
valid_typer-  r&   r'   r6   >  s&   
zMessageField.__init__c                    st   | j  t t r/t tr/| jr#|r"t|ttfr" fdd|D }nt|tr/ di |}tt	| 
|| dS )r  c                    s(   g | ]}t |tr d i |n|qS )r&   )rZ   r   )r   r   tr&   r'   
<listcomp>r  s     z(MessageField.__set__.<locals>.<listcomp>Nr&   )r5   rZ   r   r   r   r   r  r   r*  r   r  r  r-  r2  r'   r  g  s   

zMessageField.__set__c                 C   N   | j du r$t| j|  }|turt|trt|ts!td| || _ | j S )zMessage type used for field.Nr/  )	r1   r   r0  rB   r   rZ   r5   r   r   )r+   r   r&   r&   r'   r5   x  s   

zMessageField.typec                 C   ry   )zUnderlying message type used for serialization.

        Will always be a sub-class of Message.  This is different from type
        which represents the python value that message_type is mapped to for
        use by the user.
        )r5   r*   r&   r&   r'   r     s   zMessageField.message_typec                 C   s,   t || jstd| jjt|j|f |S )a"  Convert a message to a value instance.

        Used by deserializers to convert from underlying messages to
        value of expected user type.

        Args:
          message: A message instance of type self.message_type.

        Returns:
          Value of self.message_type.
        Expected type %s, got %s: %r)rZ   r   r   r"   r5   )r+   messager&   r&   r'   value_from_message     zMessageField.value_from_messagec                 C   s,   t || jstd| jjt|j|f |S )a  Convert a value instance to a message.

        Used by serializers to convert Python user types to underlying
        messages for transmission.

        Args:
          value: A value of type self.type.

        Returns:
          An instance of type self.message_type.
        r6  )rZ   r5   r   r"   r  r&   r&   r'   r     r9  zMessageField.value_to_message)FFN)r"   r#   r$   r%   r#  r
   r   r
  r  r   r"  r6   r  r  r5   r   r8  r   r.  r&   r&   r-  r'   r     s     ,(

	r   c                       sZ   e Zd ZdZeejgZejZ fddZ	 fddZ
edd Ze fdd	Z  ZS )
r   a  Field definition for enum values.

    Enum fields may have default values that are delayed until the
    associated enum type is resolved. This is necessary to support
    certain circular references.

    For example:

      class Message1(Message):

        class Color(Enum):

          RED = 1
          GREEN = 2
          BLUE = 3

        # This field default value  will be validated when default is accessed.
        animal = EnumField('Message2.Animal', 1, default='HORSE')

      class Message2(Message):

        class Animal(Enum):

          DOG = 1
          CAT = 2
          HORSE = 3

        # This fields default value will be validated right away since Color
        # is already fully resolved.
        color = EnumField(Message1.Color, 1, default='RED')
    c                    st   t |tjp|tuot |tot|t}|std| t |tjr)|| _d| _n|| _t	t
| j|fi | dS )a=  Constructor.

        Args:
          enum_type: Enum type for field.  Must be subclass of Enum.
          number: Number of field.  Must be unique per message class.
          required: Whether or not field is required.  Mutually exclusive to
            'repeated'.
          repeated: Whether or not field is repeated.  Mutually exclusive to
            'required'.
          variant: Wire-format variant hint.
          default: Default value for field if not found in stream.

        Raises:
          FieldDefinitionError when invalid enum_type is provided.
        Invalid enum type: %sN)rZ   rM   ru   r   r5   r   r   _EnumField__type_namer2   r*  r   r6   )r+   	enum_typer]   r   r1  r-  r&   r'   r6     s   zEnumField.__init__c                    s6   t |tjtjfr| jr| | |S tt| |S )a  Validate default element of Enum field.

        Enum fields allow for delayed resolution of default values
        when the type of the field has not been resolved. The default
        value of a field may be a string or an integer. If the Enum
        type of the field has been resolved, the default value is
        validated against that type.

        Args:
          value: Value to validate.

        Raises:
          ValidationError if value is not expected message type.

        )rZ   rM   ru   r[   r2   r*  r   r   r  r-  r&   r'   r     s
   
z"EnumField.validate_default_elementc                 C   r5  )zEnum type used for field.Nr:  )	r2   r   r;  rB   r   rZ   r5   r   r   )r+   
found_typer&   r&   r'   r5     s   

zEnumField.typec                    sP   z| j W S  ty'   tt| j}t|tjtjfr| 	|}|| _ | j  Y S w )zjDefault for enum field.

        Will cause resolution of Enum type and unresolved default value.
        )
r3   r@   r*  r   r  rZ   rM   ru   r[   r5   )r+   resolved_defaultr-  r&   r'   r  $  s   

zEnumField.default)r"   r#   r$   r%   r#  r
   r   r
  r  r6   r   r  r5   r  r.  r&   r&   r-  r'   r     s      
r   r   c                    s2  du st tjst trttstd | dd s+ddd  fdd}	 | }t |trEt|ttfrE|S du rOt	d	|  t tjrrj
ddd
 }|sddn4 d|dd|d
 gn&t trttr }|du rjdd
 } jdd|gn|q4)az	  Find definition by name in module-space.

    The find algorthm will look for definitions by name relative to a
    message definition or by fully qualfied name. If no definition is
    found relative to the relative_to parameter it will do the same
    search against the container of relative_to. If relative_to is a
    nested Message, it will search its message_definition(). If that
    message has no message_definition() it will search its module. If
    relative_to is a module, it will attempt to look for the
    containing module and search relative to it. If the module is a
    top-level module, it will look for the a message using a fully
    qualified name. If no message is found then, the search fails and
    DefinitionNotFoundError is raised.

    For example, when looking for any definition 'foo.bar.ADefinition'
    relative to an actual message definition abc.xyz.SomeMessage:

      find_definition('foo.bar.ADefinition', SomeMessage)

    It is like looking for the following fully qualified names:

      abc.xyz.SomeMessage. foo.bar.ADefinition
      abc.xyz. foo.bar.ADefinition
      abc. foo.bar.ADefinition
      foo.bar.ADefinition

    When resolving the name relative to Message definitions and modules, the
    algorithm searches any Messages or sub-modules found in its path.
    Non-Message values are not searched.

    A name that begins with '.' is considered to be a fully qualified
    name. The name is always searched for from the topmost package.
    For example, assume two message types:

      abc.xyz.SomeMessage
      xyz.SomeMessage

    Searching for '.xyz.SomeMessage' relative to 'abc' will resolve to
    'xyz.SomeMessage' and not 'abc.xyz.SomeMessage'.  For this kind of name,
    the relative_to parameter is effectively ignored and always set to None.

    For more information about package name resolution, please see:

      http://code.google.com/apis/protocolbuffers/docs/proto.html#packages

    Args:
      name: Name of definition to find.  May be fully qualified or relative
        name.
      relative_to: Search for definition relative to message definition or
        module. None will cause a fully qualified name search.
      importer: Import function to use for resolving modules.

    Returns:
      Enum or Message class definition associated with name.

    Raises:
      DefinitionNotFoundError if no definition is found in any search path.

    NzBrelative_to must be None, Message definition or module.  Found: %s.r   r   c               	      s   } D ]^}t | |d}|dur|} n:| du st| tjrJ| du r$|}nd| j|f }z|dd } |ddt|g} W n tyI   Y  dS w  dS t| tjsbt| tr_t	| t
tfsb dS q| S )a  Performs a single iteration searching the path from relative_to.

        This is the function that searches up the path from a relative object.

          fully.qualified.object . relative.or.nested.Definition
                                   ---------------------------->
                                                      ^
                                                      |
                                this part of search --+

        Returns:
          Message or Enum at the end of name_path, else None.
        NrK   r?  r   )rw   rZ   types
ModuleTyper"   splitstrImportErrorr5   r   r   r   )	next_partnoder_   module_namefromitemimporter	name_pathrelative_tor&   r'   search_path  s6   

z$find_definition.<locals>.search_pathTz Could not find definition for %sr@  r   )rZ   rA  rB  r5   r   r   rH   rC  r   r   r"   r   rB   r#   )r/   rM  rK  rN  foundmodule_pathparentlast_module_namer&   rJ  r'   r   6  s^   >

.	
r   )2r%   rA  r   rM   apitools.base.protorpcliter   __all__r   r   r   r   r   r   r   r   r   r   r   r   r#  rY   r  rC   r   r   r   r   r5   r4   rU   with_metaclassr8   r   r
   r   r   r   r	   r  r   r   r   r   r   r   r   r   r"  
__import__r   r&   r&   r&   r'   <module>   sn   (
ly &i  t`	  )

% +