Esempio n. 1
0
def main():
    args, protoc_args = parse_args()
    if args.decode_raw or args.encode_raw:
        message = Empty()
    else:
        message_name, protofile = args.encode or [] + args.decode or []
        protofile = Path(protofile)
        os.makedirs(str(TMP_PROTOD_DIR), exist_ok=True)
        check_output(['protoc', f'--python_out={TMP_PROTOD_DIR}'] +
                     protoc_args + [str(protofile)])
        pb2_path = TMP_PROTOD_DIR / (protofile.with_suffix('').name +
                                     '_pb2.py')
        spec = importlib.util.spec_from_file_location(
            protofile.with_suffix('').name, pb2_path)
        pb2 = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(pb2)
        message = getattr(pb2, message_name)()

    if args.decode_raw or args.decode:
        message.ParseFromString(sys.stdin.buffer.read())
    else:
        text_format.Parse(sys.stdin.read(),
                          message,
                          allow_field_number=True,
                          allow_unknown_field=True)
    if args.proto_out:
        unf_like = SimpleNamespace()
        unf_like.wire_type = wire_format.WIRETYPE_LENGTH_DELIMITED
        unf_like.data = message.SerializeToString()
        unf_like.field_number = 0
        print(render_proto(merge_definition(define(unf_like)),
                           args.proto_out == '3'),
              end='')
    elif args.decode_raw or args.decode:
        print(text_format.MessageToString(message, print_unknown_fields=True),
              end='')
    else:
        sys.stdout.buffer.write(message.SerializeToString())