Как сопоставить комментарии с полями в proto?

Помогает версия Sonnet 4.5:

  • 4 - message_type
  • 2 - field в message
  • 5 - enum_type
  • 8 - service

try (InputStream is = ...) {
DescriptorProtos.FileDescriptorSet fileDescriptorSet =
DescriptorProtos.FileDescriptorSet.parseFrom(is);

for (DescriptorProtos.FileDescriptorProto fileProto : fileDescriptorSet.getFileList()) {
// Получаем SourceCodeInfo с комментариями
DescriptorProtos.SourceCodeInfo sourceCodeInfo = fileProto.getSourceCodeInfo();

// Создаем карту: path -> комментарии
Map<List<Integer>, String> pathToComments = new HashMap<>();
for (DescriptorProtos.SourceCodeInfo.Location location : sourceCodeInfo.getLocationList()) {
if (location.hasLeadingComments() || location.hasTrailingComments()) {
List<Integer> path = location.getPathList();
String comment = location.hasLeadingComments()
? location.getLeadingComments()
: location.getTrailingComments();
pathToComments.put(path, comment);
}
}

// Обходим поля в сообщениях
for (int msgIndex = 0; msgIndex < fileProto.getMessageTypeCount(); msgIndex++) {
DescriptorProtos.DescriptorProto messageProto = fileProto.getMessageType(msgIndex);

for (int fieldIndex = 0; fieldIndex < messageProto.getFieldCount(); fieldIndex++) {
// Path для поля: [4, msgIndex, 2, fieldIndex]
// 4 = message_type, 2 = field
List<Integer> fieldPath = Arrays.asList(4, msgIndex, 2, fieldIndex);
String comment = pathToComments.get(fieldPath);

DescriptorProtos.FieldDescriptorProto fieldProto =
messageProto.getField(fieldIndex);
System.out.println("Field: " + fieldProto.getName() +
", Comment: " + comment);
}
}
}
}