Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ggj][codegen] feat: add protobuf comments to ServiceClient #310

Merged
merged 15 commits into from
Sep 19, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/main/java/com/google/api/generator/engine/ast/TypeNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import javax.annotation.Nullable;

@AutoValue
public abstract class TypeNode implements AstNode {
public abstract class TypeNode implements AstNode, Comparable<TypeNode> {
static final Reference EXCEPTION_REFERENCE = ConcreteReference.withClazz(Exception.class);
public static final Reference WILDCARD_REFERENCE = ConcreteReference.wildcard();

Expand Down Expand Up @@ -88,6 +88,31 @@ public enum TypeKind {
@Nullable
public abstract Reference reference();

@Override
public int compareTo(TypeNode other) {
// Ascending order of name.
if (isPrimitiveType()) {
if (other.isPrimitiveType()) {
return typeKind().name().compareTo(other.typeKind().name());
}
// b is a reference type or null, so a < b.
return -1;
}

if (this.equals(TypeNode.NULL)) {
// Can't self-compare, so we don't need to check whether the other one is TypeNode.NULL.
return other.isPrimitiveType() ? 1 : -1;
}

if (other.isPrimitiveType() || other.equals(TypeNode.NULL)) {
return 1;
}

// Both are reference types.
// TODO(miraleung): Replace this with a proper reference Comaparator.
return reference().fullName().compareTo(other.reference().fullName());
}

public static Builder builder() {
return new AutoValue_TypeNode.Builder().setIsArray(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public GapicClass generate(Service service, Map<String, Message> messageTypes) {

ClassDefinition classDef =
ClassDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createClassHeaderComments(service))
.setPackageString(pakkage)
.setAnnotations(createClassAnnotations(types))
.setImplementsTypes(createClassImplements(types))
Expand Down Expand Up @@ -471,7 +473,26 @@ private static List<MethodDefinition> createMethodVariants(
Preconditions.checkNotNull(
inputMessage, String.format("Message %s not found", methodInputTypeName));

for (List<MethodArgument> signature : method.methodSignatures()) {
// Make the method signature order deterministic, which helps with unit testing and per-version
// diffs.
List<List<MethodArgument>> sortedMethodSignatures =
method.methodSignatures().stream()
.sorted(
(s1, s2) -> {
if (s1.size() != s2.size()) {
return s1.size() - s2.size();
}
for (int i = 0; i < s1.size(); i++) {
int compareVal = s1.get(i).compareTo(s2.get(i));
if (compareVal != 0) {
return compareVal;
}
}
return 0;
})
.collect(Collectors.toList());

for (List<MethodArgument> signature : sortedMethodSignatures) {
// Get the argument list.
List<VariableExpr> arguments =
signature.stream()
Expand Down Expand Up @@ -563,6 +584,8 @@ private static List<MethodDefinition> createMethodVariants(

javaMethods.add(
MethodDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createRpcMethodHeaderComment(method, signature))
.setScope(ScopeNode.PUBLIC)
.setIsFinal(true)
.setReturnType(methodOutputType)
Expand Down Expand Up @@ -593,6 +616,8 @@ private static List<MethodDefinition> createMethodVariants(
.build();
javaMethods.add(
MethodDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createRpcMethodHeaderComment(method))
.setScope(ScopeNode.PUBLIC)
.setIsFinal(true)
.setReturnType(methodOutputType)
Expand All @@ -606,6 +631,7 @@ private static List<MethodDefinition> createMethodVariants(

private static MethodDefinition createLroAsyncMethod(
String serviceName, Method method, Map<String, TypeNode> types) {
// TODO(miraleung): Create variants as well.
Preconditions.checkState(
method.hasLro(), String.format("Method %s does not have an LRO", method.name()));
String methodName = JavaStyle.toLowerCamelCase(method.name());
Expand Down Expand Up @@ -640,6 +666,8 @@ private static MethodDefinition createLroAsyncMethod(
.build();

return MethodDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createRpcMethodHeaderComment(method))
.setScope(ScopeNode.PUBLIC)
.setIsFinal(true)
.setReturnType(returnType)
Expand Down Expand Up @@ -711,6 +739,8 @@ private static MethodDefinition createCallableMethod(
.build();

return MethodDefinition.builder()
.setHeaderCommentStatements(
ServiceClientCommentComposer.createRpcCallableMethodHeaderComment(method))
.setScope(ScopeNode.PUBLIC)
.setIsFinal(true)
.setName(methodName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,70 @@
import com.google.api.generator.engine.ast.CommentStatement;
import com.google.api.generator.engine.ast.JavaDocComment;
import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.gapic.model.Method;
import com.google.api.generator.gapic.model.MethodArgument;
import com.google.api.generator.gapic.model.Service;
import com.google.api.generator.gapic.utils.JavaStyle;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class ServiceClientCommentComposer {
// Tokens.
private static final String COLON = ":";
private static final String EMPTY_STRING = "";
private static final String API_EXCEPTION_TYPE_NAME = "com.google.api.gax.rpc.ApiException";
private static final String EXCEPTION_CONDITION = "if the remote call fails";

// Constants.
private static final String SERVICE_DESCRIPTION_INTRO_STRING =
"This class provides the ability to make remote calls to the backing service through method "
+ "calls that map to API methods. Sample code to get started:";
private static final String SERVICE_DESCRIPTION_CLOSE_STRING =
"Note: close() needs to be called on the echoClient object to clean up resources such as "
+ "threads. In the example above, try-with-resources is used, which automatically calls "
+ "close().";
private static final String SERVICE_DESCRIPTION_SURFACE_SUMMARY_STRING =
"The surface of this class includes several types of Java methods for each of the API's "
+ "methods:";
private static final String SERVICE_DESCRIPTION_SURFACE_CODA_STRING =
"See the individual methods for example code.";
private static final String SERVICE_DESCRIPTION_RESOURCE_NAMES_FORMATTING_STRING =
"Many parameters require resource names to be formatted in a particular way. To assist with"
+ " these names, this class includes a format method for each type of name, and"
+ " additionally a parse method to extract the individual identifiers contained within"
+ " names that are returned.";
private static final String SERVICE_DESCRIPTION_CREDENTIALS_SUMMARY_STRING =
"To customize credentials:";
private static final String SERVICE_DESCRIPTION_ENDPOINT_SUMMARY_STRING =
"To customize the endpoint:";

private static final String METHOD_DESCRIPTION_SAMPLE_CODE_SUMMARY_STRING = "Sample code:";

private static final List<String> SERVICE_DESCRIPTION_SURFACE_DESCRIPTION =
Arrays.asList(
"A \"flattened\" method. With this type of method, the fields of the request type have"
+ " been converted into function parameters. It may be the case that not all fields"
+ " are available as parameters, and not every API method will have a flattened"
+ " method entry point.",
"A \"request object\" method. This type of method only takes one parameter, a request"
+ " object, which must be constructed before the call. Not every API method will"
+ " have a request object method.",
"A \"callable\" method. This type of method takes no parameters and returns an immutable "
+ "API callable object, which can be used to initiate calls to the service.");

// Patterns.
private static final String CREATE_METHOD_STUB_ARG_PATTERN =
"Constructs an instance of EchoClient, using the given stub for making calls. This is for"
+ " advanced usage - prefer using create(%s).";

private static final String SERVICE_DESCRIPTION_CUSTOMIZE_SUMMARY_PATTERN =
"This class can be customized by passing in a custom instance of %s to create(). For"
+ " example:";

private static final String SERVICE_DESCRIPTION_SUMMARY_PATTERN = "Service Description: %s";

// Comments.
static final CommentStatement CREATE_METHOD_NO_ARG_COMMENT =
toSimpleComment("Constructs an instance of EchoClient with default settings.");

Expand All @@ -45,11 +101,93 @@ class ServiceClientCommentComposer {
"Returns the OperationsClient that can be used to query the status of a long-running"
+ " operation returned by another API method call.");

static List<CommentStatement> createClassHeaderComments(Service service) {
JavaDocComment.Builder classHeaderJavadocBuilder = JavaDocComment.builder();
if (service.hasDescription()) {
classHeaderJavadocBuilder.addComment(
String.format(SERVICE_DESCRIPTION_SUMMARY_PATTERN, service.description()));
}

// Service introduction.
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_INTRO_STRING);
// TODO(summerji): Add sample code here.

// API surface description.
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_CLOSE_STRING);
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_SURFACE_SUMMARY_STRING);
classHeaderJavadocBuilder.addOrderedList(SERVICE_DESCRIPTION_SURFACE_DESCRIPTION);
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_SURFACE_CODA_STRING);

// Formatting resource names.
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_RESOURCE_NAMES_FORMATTING_STRING);

// Customization examples.
classHeaderJavadocBuilder.addParagraph(
String.format(
SERVICE_DESCRIPTION_CUSTOMIZE_SUMMARY_PATTERN,
String.format("%sSettings", JavaStyle.toUpperCamelCase(service.name()))));
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_CREDENTIALS_SUMMARY_STRING);
// TODO(summerji): Add credentials' customization sample code here.
classHeaderJavadocBuilder.addParagraph(SERVICE_DESCRIPTION_ENDPOINT_SUMMARY_STRING);
// TODO(summerji): Add endpoint customization sample code here.

return Arrays.asList(
CommentComposer.AUTO_GENERATED_CLASS_COMMENT,
CommentStatement.withComment(classHeaderJavadocBuilder.build()));
}

static CommentStatement createCreateMethodStubArgComment(TypeNode settingsType) {
return toSimpleComment(
String.format(CREATE_METHOD_STUB_ARG_PATTERN, settingsType.reference().name()));
}

static List<CommentStatement> createRpcMethodHeaderComment(
Method method, List<MethodArgument> methodArguments) {
JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder();

if (method.hasDescription()) {
methodJavadocBuilder.addComment(method.description());
}

methodJavadocBuilder.addParagraph(METHOD_DESCRIPTION_SAMPLE_CODE_SUMMARY_STRING);
// TODO(summerji): Add sample code here.

if (methodArguments.isEmpty()) {
methodJavadocBuilder.addParam(
"request", "The request object containing all of the parameters for the API call.");
} else {
for (MethodArgument argument : methodArguments) {
methodJavadocBuilder.addParam(
argument.name(), argument.hasDescription() ? argument.description() : EMPTY_STRING);
}
}

methodJavadocBuilder.setThrows(API_EXCEPTION_TYPE_NAME, EXCEPTION_CONDITION);

return Arrays.asList(
CommentComposer.AUTO_GENERATED_METHOD_COMMENT,
CommentStatement.withComment(methodJavadocBuilder.build()));
}

static List<CommentStatement> createRpcMethodHeaderComment(Method method) {
return createRpcMethodHeaderComment(method, Collections.emptyList());
}

static List<CommentStatement> createRpcCallableMethodHeaderComment(Method method) {
JavaDocComment.Builder methodJavadocBuilder = JavaDocComment.builder();

if (method.hasDescription()) {
methodJavadocBuilder.addComment(method.description());
}

methodJavadocBuilder.addParagraph(METHOD_DESCRIPTION_SAMPLE_CODE_SUMMARY_STRING);
// TODO(summerji): Add sample code here.

return Arrays.asList(
CommentComposer.AUTO_GENERATED_METHOD_COMMENT,
CommentStatement.withComment(methodJavadocBuilder.build()));
}

private static CommentStatement toSimpleComment(String comment) {
return CommentStatement.withComment(JavaDocComment.withComment(comment));
}
Expand Down
9 changes: 9 additions & 0 deletions src/main/java/com/google/api/generator/gapic/model/Field.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ public abstract class Field {
@Nullable
public abstract ResourceReference resourceReference();

@Nullable
public abstract String description();

public boolean hasDescription() {
return description() != null;
}

public boolean hasResourceReference() {
return type().equals(TypeNode.STRING) && resourceReference() != null;
}
Expand All @@ -51,6 +58,8 @@ public abstract static class Builder {

public abstract Builder setResourceReference(ResourceReference resourceReference);

public abstract Builder setDescription(String description);

public abstract Field build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public enum Stream {
@Nullable
public abstract LongrunningOperation lro();

@Nullable
public abstract String description();

// Example from Expand in echo.proto: Thet TypeNodes that map to
// [["content", "error"], ["content", "error", "info"]].
public abstract ImmutableList<List<MethodArgument>> methodSignatures();
Expand All @@ -50,7 +53,9 @@ public boolean hasLro() {
return lro() != null;
}

// TODO(miraleung): Parse annotations, comments.
public boolean hasDescription() {
return description() != null;
}

public static Builder builder() {
return new AutoValue_Method.Builder()
Expand Down Expand Up @@ -84,6 +89,8 @@ public abstract static class Builder {

public abstract Builder setLro(LongrunningOperation lro);

public abstract Builder setDescription(String description);

public abstract Builder setMethodSignatures(List<List<MethodArgument>> methodSignature);

public abstract Builder setIsPaged(boolean isPaged);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import java.util.List;
import javax.annotation.Nullable;

@AutoValue
public abstract class MethodArgument {
public abstract class MethodArgument implements Comparable<MethodArgument> {
public abstract String name();

public abstract TypeNode type();
Expand All @@ -32,6 +33,22 @@ public abstract class MethodArgument {
// Returns true if this is a resource name helper tyep.
public abstract boolean isResourceNameHelper();

@Nullable
public abstract String description();

public boolean hasDescription() {
return description() != null;
}

@Override
public int compareTo(MethodArgument other) {
int compareVal = type().compareTo(other.type());
if (compareVal == 0) {
compareVal = name().compareTo(other.name());
}
return compareVal;
}

public static Builder builder() {
return new AutoValue_MethodArgument.Builder()
.setNestedTypes(ImmutableList.of())
Expand All @@ -48,6 +65,8 @@ public abstract static class Builder {

public abstract Builder setIsResourceNameHelper(boolean isResourceNameHelper);

public abstract Builder setDescription(String description);

public abstract MethodArgument build();
}
}
Loading