ProtoField.java

package net.morimekta.proto;

import com.google.protobuf.Descriptors;

import java.util.Locale;

import static net.morimekta.proto.utils.FieldUtil.getMapKeyDescriptor;
import static net.morimekta.proto.utils.FieldUtil.getMapValueDescriptor;

public class ProtoField {
    /**
     * Make a string representation of a proto field.
     * @param field Field descriptor to stringify.
     * @return The field string value.
     */
    public static String toString(Descriptors.FieldDescriptor field) {
        return fieldTypeToString(field) + " " +
               field.getName() + " = " +
               field.getNumber();
    }

    /**
     * Make a string representation of the type of a proto message field.
     * @param field Field descriptor to stringify.
     * @return The field type string value.
     */
    public static String fieldTypeToString(Descriptors.FieldDescriptor field) {
        if (field.isMapField()) {
            var keyType   = getMapKeyDescriptor(field);
            var valueType = getMapValueDescriptor(field);
            return "map<" + fieldTypeToString(keyType) + ", " + fieldTypeToString(valueType) + ">";
        }
        var prefix = "";
        var suffix = "";
        if (field.isRepeated()) {
            prefix = "list<";
            suffix = ">";
        } else if (field.isRequired()) {
            prefix = "required ";
        } else if (field.getFile().getSyntax() == Descriptors.FileDescriptor.Syntax.PROTO2 &&
                   field.isOptional()) {
            // Optional exists, but has no real effect in PROTO3 (all non-repeated fields are optional),
            // except for adding 'has*' methods.
            prefix = "optional ";
        }
        switch (field.getType()) {
            case MESSAGE: {
                var md = field.getMessageType();
                return prefix + md.getFullName() + suffix;
            }
            case ENUM: {
                var ed = field.getEnumType();
                return prefix + ed.getFullName() + suffix;
            }
            default: {
                return prefix + field.getType().name().toLowerCase(Locale.US) + suffix;
            }
        }
    }
}