def get_compiled_proto(): # Compile trezor.proto to binary format pdir = os.path.abspath(TREZOR_PROTO_DIR) pfile = os.path.join(pdir, "messages.proto") cmd = "protoc --include_imports -I" + PROTOBUF_PROTO_DIR + " -I" + pdir + " " + pfile + " -otrezor.bin" subprocess.check_call(cmd.split()) # Load compiled protocol description to string proto = open('trezor.bin', 'r').read() os.unlink('trezor.bin') # Parse it into FileDescriptorSet structure compiled = FileDescriptorSet() compiled.ParseFromString(proto) return compiled
def register_descriptor_data(self, type_url, descriptor_data): if type_url not in self._type_url_to_descriptor_data: is_binary = ( isinstance(descriptor_data, six.string_types) or isinstance(descriptor_data, six.binary_type) or isinstance(descriptor_data, bytearray)) if is_binary: from google.protobuf.descriptor_pb2 import FileDescriptorSet fds = FileDescriptorSet() fds.ParseFromString(descriptor_data) descriptor_data = fds self._type_url_to_descriptor_data[type_url] = descriptor_data if self._dynamic_factory is None: self._dynamic_factory = DynamicMessageFactory() self._dynamic_factory.register_type(type_url, descriptor_data)
def read_descriptor_pool(self): dpool = descriptor_pool.DescriptorPool() while True: vtype, data = self._read_next_obj() if vtype is None: raise Exception("Unexpected end of file") if vtype == T_FILE_DESCRIPTOR: ds = FileDescriptorSet() ds.ParseFromString(data) for df in ds.file: dpool.Add(df) return dpool, data elif vtype == T_PROTOBUF_VERSION: pbversion = data.decode("utf8") if google.protobuf.__version__.split(".") < pbversion.split( "."): warnings.warn( f"File uses more recent of protobuf ({pbversion})") else: raise Exception(f"Unknown message type {vtype}")
#!/usr/bin/env python3 import sys import generator.File from google.protobuf.descriptor_pb2 import FileDescriptorSet base_file = sys.argv[1] with open("{}.pb".format(base_file), "rb") as f: # Load the descriptor protobuf file d = FileDescriptorSet() d.ParseFromString(f.read()) # Check that there is only one file assert len(d.file) == 1 # Load the file b = generator.File.File(d.file[0], base_file) # Generate the c++ file header, impl, python = b.generate_cpp() with open("{}.h".format(base_file), "w") as f: f.write(header) with open("{}.cpp".format(base_file), "w") as f: f.write(impl) with open("{}.py.cpp".format(base_file), "w") as f: f.write(python)