Coverage for ion/core/object/object_utils : 68.68%
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
|
#!/usr/bin/env python @file ion/core/object/object_utils.py @brief Tools and utilities for object management @author David Stuebe """
# Globals
""" Exceptions specific to Object Utilities. """ pass
""" An exception class for errors that occur in the Object Wrapper class """
''' Improve performance on GPBType comparisons enormously. '''
#return hash(repr(self))
#setattr(containers.RepeatedCompositeFieldContainer, '__hash__', __hash_by_id) #setattr(containers.RepeatedScalarFieldContainer, '__hash__', __hash_by_id)
""" This method is deprecated def sha1(val, bin=True): if isinstance(val, BaseObject): val = val.value if bin: return sha1bin(val) return sha1hex(val) """
"""binary form (20 bytes) of sha1 digest to hex string (40 char) """
def get_enum_from_descriptor(descriptor): """ @TODO Needs cleaning up - should be more robust + get the version """
raise ObjectUtilException(\ '''This object has no Message Type Identifier enum: %s'''\ % (str(descriptor.name)))
def get_type_from_descriptor(descriptor): """ Operates on instances and classes of gpb messages! @TODO Needs cleaning up - should be more robust + get the version """
gpb_type = type else:
""" This returns an unwrapped GPB object to the application level """
# Temporary restriction to version == 1. Temporary sanity check! msg = '''Protocol Buffer Object VERSION in the MessageTypeIdentifier should be 1. \n''' msg += '''Explicit versioning is not yet supported.\n''' msg +='''Arguments to create_type_identifier: object_id - "%s"; version - "%s"'''\ % (str(object_id), str(version)) raise ObjectUtilException(msg)
#ObjectType = type_pb2.GPBType(int(object_id), int(version)) except ValueError, ex: raise ObjectUtilException(\ '''Protocol Buffer Object IDs must be integers:object_id - "%s"; version - "%s"'''\ % (str(object_id), str(version)))
""" To be called once on package initialization. The given package must include a list named "protos" specifying which protocol buffer files to import. @param rootpath The full path of the package to import the Protocol Buffers classes from. """
global gpb_id_to_class
old_def = str(gpb_id_to_class[val.number].__module__) new_def = str(msg_class.__module__) gpb_num = str(val.number) raise ObjectUtilException('Duplicate _MessageTypeIdentifier for '\ + 'ID# %s in %s; original definition in %s' \ % (gpb_num, new_def, old_def))
# Eventually this will implement versioning... # For now return an error if the version is not 1 msg = '''Protocol Buffer Object VERSION in the MessageTypeIdentifier should be 1. \n''' msg += '''Explicit versioning is not yet supported.\n''' msg +='''Invalid Object Class: "%s"'''\ % (str(msg_class.__name__)) raise ObjectUtilException(msg)
""" Get a callable google.protobuf.message.Message subclass with the given MessageTypeIdentifier enum id. @param id The type id object @retval msg_class The class for the given id. @throws ObjectUtilException """ return gpb_id_to_class[typeid] else: raise ObjectUtilException('The type argument is not a valid type identifier object: "%s, type: %s "' % (str(typeid), type(typeid)))
""" Fuzzy search for a GPB-defined type with the given text in the name. Assumes that build_gpb_lookup() was called on package init. """ import difflib
global type_name_cache if type_name_cache is None: type_name_cache = dict((cls.__name__.lower(), cls) for cls in gpb_id_to_class.itervalues())
matches = difflib.get_close_matches(query.lower(), type_name_cache.iterkeys(), cutoff=0.5) clses = (type_name_cache[match] for match in matches) return dict((cls._ID, cls) for cls in clses)
""" Similar to open_proto, but instead return the contents of the proto file as a simple string. """ gpb_root = os.path.join('..', 'ion-object-definitions', 'net') cls = get_gpb_class_from_type_id(typeid) proto_pieces = cls.__module__.split('.')[1:] filename = proto_pieces.pop() proto = '%s.proto' % (filename.replace('_pb2', '')) proto_dir = os.sep.join(proto_pieces) proto_path = os.path.join(gpb_root, proto_dir, proto) if os.path.exists(proto_path): return open(proto_path).read() else: py_dir = __import__(cls.__module__).__path__[0] py_file = '%s.py' % (filename) py_path = os.path.join(py_dir, proto_dir, py_file) return open(py_path).read()
""" Developer utility to open either the .proto if found, or the generated .py, for a GPB typeid. """
def launch(path): import platform
if platform.system() == 'Windows': os.system('notepad %s' % path) else: os.system('open -t %s' % path)
gpb_root = os.path.join('..', 'ion-object-definitions', 'net') cls = get_gpb_class_from_type_id(typeid) proto_pieces = cls.__module__.split('.')[1:] filename = proto_pieces.pop() proto = '%s.proto' % (filename.replace('_pb2', '')) proto_dir = os.sep.join(proto_pieces) proto_path = os.path.join(gpb_root, proto_dir, proto) if os.path.exists(proto_path): launch(proto_path) else: py_dir = __import__(cls.__module__).__path__[0] py_file = '%s.py' % (filename) py_path = os.path.join(py_dir, proto_dir, py_file) launch(py_path)
''' print 'GPB SOURCE' print 'func name', func_name, func print 'args', args print 'kwargs', kwargs ''' log.error(source.Debug()) raise OOIObjectError('Can not access Invalidated Object in function "%s"' % func_name)
''' print 'GPB SOURCE ROOT'
print 'func name', func_name, func print 'args', args print 'kwargs', kwargs '''
# Build the lookup table on first import
# Build the CDM TYPES for import |