Search code examples
protocol-buffersnanopb

Protocol buffer split oneof message to a different file


I use nanopb and a .proto file that looks like this (simplified):

syntax = "proto3";

message Type1
{
    bool a = 1;
}

message Type2
{
    int32 b = 1;
}

message Message
{
    int32 id = 1;
    oneof oneMessage {
        Type1 messageType1 = 2;
        Type2 messageType2 = 3;
    }
}

I now need to split the oneMessage to a different .proto file and import it. I can do something like: file a.proto:

syntax = "proto3";
import "b.proto"
message Message
{
    int32 id = 1;
    oneofTypeMessage aMessage = 2;
}

file b.proto

syntax = "proto3";

message Type1
{
    bool a = 1;
}

message Type2
{
    int32 b = 1;
}

message oneofTypeMessage
{
    oneof oneMessage {
        Type1 messageType1 = 2;
        Type2 messageType2 = 3;
    }
}

But this means I can't get to my message types with message.messageType1, triggering lots of changes in the existing source code. How can I split the oneof part to another file without changing the way I access to it? I've tried declaring Message in both files but it is not permitted.


Solution

  • No. oneMessage is not a message type, and to import something from another file, it must be a message type. Adding a new oneofTypeMessage would add an additional node in the graph, and would not be data-compatible with the original data.

    You can move Type1 and Type2, but the oneof must stay as-was; so: this is valid:

    file a.proto:

    syntax = "proto3";
    import "b.proto"
    message Message
    {
        int32 id = 1;
        oneof oneMessage {
            Type1 messageType1 = 2;
            Type2 messageType2 = 3;
        }
    }
    

    file b.proto:

    syntax = "proto3";
    
    message Type1
    {
        bool a = 1;
    }
    
    message Type2
    {
        int32 b = 1;
    }