def load_descriptor(self,
                        descriptor_blob,
                        fold_comments=True,
                        type_tag_name='_type'):

        # decode file descriptor set or if that is not possible,
        # try plugin request
        try:
            message = descriptor_pb2.FileDescriptorSet()
            message.ParseFromString(descriptor_blob)
        except DecodeError:
            message = CodeGeneratorRequest()
            message.ParseFromString(descriptor_blob)

        d = self.parse(message, type_tag_name=type_tag_name)
        print d.keys()
        for _file in d.get('file', None) or d['proto_file']:
            if fold_comments:
                self.fold_comments_in(_file)
            self.catalog[_file['package']] = _file
Exemple #2
0
def test_invalid_request():
    with pytest.raises(
        ConfigurationError, match="Runtime parameter is not specified",
    ):
        process(CodeGeneratorRequest())

    with pytest.raises(
        ConfigurationError, match="Unknown runtime",
    ):
        process(CodeGeneratorRequest(parameter="runtime=invalid"))

    with pytest.raises(
        ConfigurationError, match="Missing configuration message",
    ):
        process(
            CodeGeneratorRequest(
                parameter="runtime=python",
                file_to_generate=["svc.proto"],
                proto_file=[dict(name="svc.proto")],
            )
        )
Exemple #3
0
def main() -> None:
    with os.fdopen(sys.stdin.fileno(), 'rb') as inp:
        request = CodeGeneratorRequest.FromString(inp.read())

    types_map: Dict[str, str] = {}
    for pf in request.proto_file:
        for mt in pf.message_type:
            types_map.update(_type_names(pf, mt))

    response = CodeGeneratorResponse()

    # See https://github.com/protocolbuffers/protobuf/blob/v3.12.0/docs/implementing_proto3_presence.md  # noqa
    if hasattr(CodeGeneratorResponse, 'Feature'):
        response.supported_features = (  # type: ignore
            CodeGeneratorResponse.FEATURE_PROTO3_OPTIONAL  # type: ignore
        )

    for file_to_generate in request.file_to_generate:
        proto_file = _get_proto(request, file_to_generate)

        imports = [
            _proto2pb2_module_name(dep)
            for dep in list(proto_file.dependency) + [file_to_generate]
        ]

        services = []
        for service in proto_file.service:
            methods = []
            for method in service.method:
                cardinality = _CARDINALITY[(method.client_streaming,
                                            method.server_streaming)]
                methods.append(
                    Method(
                        name=method.name,
                        cardinality=cardinality,
                        request_type=types_map[method.input_type],
                        reply_type=types_map[method.output_type],
                    ))
            services.append(Service(name=service.name, methods=methods))

        file = response.file.add()
        module_name = _proto2grpc_module_name(file_to_generate)
        file.name = module_name.replace(".", "/") + ".py"
        file.content = render(
            proto_file=proto_file.name,
            package=proto_file.package,
            imports=imports,
            services=services,
        )

    with os.fdopen(sys.stdout.fileno(), 'wb') as out:
        out.write(response.SerializeToString())
Exemple #4
0
def main(input_file=sys.stdin, output_file=sys.stdout):
    request = CodeGeneratorRequest.FromString(input_file.buffer.read())
    answer = []
    for fname in request.file_to_generate:
        answer.append(
            CodeGeneratorResponse.File(
                name=fname.replace('.proto', '_pb2.py'),
                insertion_point='module_scope',
                content="# Hello {}, I'm a dummy plugin!".format(fname),
            ))

    cgr = CodeGeneratorResponse(file=answer)
    output_file.buffer.write(cgr.SerializeToString())
Exemple #5
0
def main() -> None:
    with os.fdopen(sys.stdin.fileno(), 'rb') as inp:
        request = CodeGeneratorRequest.FromString(inp.read())

    types_map: Dict[str, str] = {}
    for pf in request.proto_file:
        for mt in pf.message_type:
            types_map.update(_type_names(pf, mt))

    response = CodeGeneratorResponse()
    for file_to_generate in request.file_to_generate:
        proto_file = _get_proto(request, file_to_generate)

        imports = [
            _proto2pb2_module_name(dep)
            for dep in list(proto_file.dependency) + [file_to_generate]
        ]

        services = []
        for service in proto_file.service:
            methods = []
            for method in service.method:
                cardinality = _CARDINALITY[(method.client_streaming,
                                            method.server_streaming)]
                methods.append(
                    Method(
                        name=method.name,
                        cardinality=cardinality,
                        request_type=types_map[method.input_type],
                        reply_type=types_map[method.output_type],
                    ))
            services.append(Service(name=service.name, methods=methods))

        file = response.file.add()
        module_name = _proto2grpc_module_name(file_to_generate)
        file.name = module_name.replace(".", "/") + ".py"
        file.content = render(
            proto_file=proto_file.name,
            package=proto_file.package,
            imports=imports,
            services=services,
        )

    with os.fdopen(sys.stdout.fileno(), 'wb') as out:
        out.write(response.SerializeToString())
Exemple #6
0
def main() -> None:
    with os.fdopen(sys.stdin.fileno(), 'rb') as inp:
        request = CodeGeneratorRequest.FromString(inp.read())

    types_map = {
        _type_name(pf, mt): '.'.join((_proto2py(pf.name), mt.name))
        for pf in request.proto_file for mt in pf.message_type
    }

    response = CodeGeneratorResponse()
    for file_to_generate in request.file_to_generate:
        proto_file = _get_proto(request, file_to_generate)

        imports = [
            _proto2py(dep)
            for dep in list(proto_file.dependency) + [file_to_generate]
        ]

        services = []
        for service in proto_file.service:
            methods = []
            for method in service.method:
                cardinality = _CARDINALITY[(method.client_streaming,
                                            method.server_streaming)]
                methods.append(
                    Method(
                        name=method.name,
                        cardinality=cardinality,
                        request_type=types_map[method.input_type],
                        reply_type=types_map[method.output_type],
                    ))
            services.append(Service(name=service.name, methods=methods))

        file = response.file.add()
        file.name = file_to_generate.replace('.proto', SUFFIX)
        file.content = render(
            proto_file=proto_file.name,
            package=proto_file.package,
            imports=imports,
            services=services,
        )

    with os.fdopen(sys.stdout.fileno(), 'wb') as out:
        out.write(response.SerializeToString())
Exemple #7
0
 def test_is_mixed_case(self):
     cgp = parser.CodeGeneratorParser(CodeGeneratorRequest())
     assert cgp._is_mixed_case('foo') is False
     assert cgp._is_mixed_case('FOO') is False
     assert cgp._is_mixed_case('Foo') is True
Exemple #8
0
def python_request(proto_file_name, message_proto):
    return CodeGeneratorRequest(
        parameter="runtime=python",
        file_to_generate=[proto_file_name],
        proto_file=message_proto.file,
    )
#!/usr/bin/env python
# encoding: utf-8
import sys
from google.protobuf.compiler.plugin_pb2 import CodeGeneratorRequest, CodeGeneratorResponse
import google.protobuf.descriptor_pb2 as descriptor

FieldD = descriptor.FieldDescriptorProto

request = CodeGeneratorRequest()
request.ParseFromString(sys.stdin.read())
response = CodeGeneratorResponse()

for file in request.proto_file:
    out = ''
    out += str(FieldD)
    out += """package io.devision.gen;\n\n"""
    out += """import java.util.Date;\n"""
    out += """import javax.persistence.Column;\n"""
    out += """import javax.persistence.Entity;\n"""
    out += """import javax.persistence.Id;\n"""
    out += """import javax.persistence.Table;\n"""
    # for enum in file.enum_type:
    #     out += 'enum ' + enum.name + '\n'
    #     for value in enum.value:
    #         out += '\t' + value.name + '\n'

    type_name = None
    for message in file.message_type:
        type_name = message.name
        if type_name == 'Column':
            continue
Exemple #10
0
def main() -> None:
    with os.fdopen(sys.stdin.fileno(), "rb") as inp:
        request = CodeGeneratorRequest.FromString(inp.read())
    response = process(request)
    with os.fdopen(sys.stdout.fileno(), "wb") as out:
        out.write(response.SerializeToString())