Search code examples
protocol-buffersprotobuf-javacustom-options

How to specify multiple enum values for EnumValueOptions inside a Protobuf file


I want to pass on multiple enum value options as per below inside a proto file,
but i find compilations errors, while specifying values as per (types) = [5,6] inside below code block :

    extend google.protobuf.EnumValueOptions {
      optional string name = 50001;
      repeated int32 types = 50002; 
    }

    enum FileDefinitionSubType {
        UNKNOWN = 0;
        MAIN = 1 [
          (name) = "main",
          (types) = [5,6]                   // Compilation error in this line 
        ];
      } here

Can someone suggest how to fix this problem. Below is a sample enum that i have in my java code, which i want to replicate in proto file.

enum CarType {
      UNKNOWN = 0;
      NEW = 1 ("new", [MARUTI_ALTO, FORD_ECOSPORT]);
      OLD = 2 ("old", [MARUTI_800, FORD_FIGO]);
      MIDAGE = 3 ("midAge", []);
}

enum CarModel {
      UNKNOWN = 0;
      MARUTI_800 = 1;
      MARUTI_ALTO = 2;
      FORD_ECOSPORT = 3;
      FORD_FIGO = 4;
}

I already tried giving passing different set of values, but nothing worked.


Solution

  • According to language specification:

    To set multiple values when an option field is repeated, use multiple option declarations with the name of that field.

    Which means this:

    enum FileDefinitionSubType {
        UNKNOWN = 0;
        MAIN = 1 [
          (name) = "main",
          (types) = 5,
          (types) = 6
        ];
      }
    

    The separate values will get collected into the repeated list, as can be verified by protoc --decode:

    $ protoc -otest.pb test.proto
    $ protoc --decode=google.protobuf.FileDescriptorSet google/protobuf/descriptor.proto < test.pb
    ...
      enum_type {
        name: "FileDefinitionSubType"
        ...
        value {
          name: "MAIN"
          number: 1
          options {
            50001: "main"
            50002: 1
            50002: 2
          }
        }
      }
    ...
    

    Alternatively you can put all of your options inside a submessage, and use the "protocol buffers text format" to give the values:

    message MyOptions {
        optional string name = 1;
        repeated int32 types = 2; 
    }
    
    extend google.protobuf.EnumValueOptions {
        optional MyOptions myopt = 50001;
    }
    
    enum MyEnum
    {
        MyValue = 1 [(myopt) = {name: "main", types: [1,2]}];
    }