ProtoField.java
/*
* Copyright 2025 Proto Utils Authors
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
/**
* Utility for making string representations of proto field descriptors.
*/
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;
}
}
}
}