Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
2cb0d9f
draft version
summer-ji-eng Nov 10, 2020
2bf804e
Add unit test for long line
summer-ji-eng Nov 10, 2020
b0c6b47
Implement formatter for code snippet
summer-ji-eng Nov 10, 2020
94bd9ed
Add license and comment
summer-ji-eng Nov 10, 2020
209ec9d
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 10, 2020
7176a85
Use string as input parameters
summer-ji-eng Nov 10, 2020
62da37b
remove unused dep
summer-ji-eng Nov 10, 2020
c9213eb
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 11, 2020
07d9d21
draft version
summer-ji-eng Nov 10, 2020
55c7604
Add unit test for long line
summer-ji-eng Nov 10, 2020
9f1b49d
Implement formatter for code snippet
summer-ji-eng Nov 10, 2020
3126e5f
Add license and comment
summer-ji-eng Nov 10, 2020
308e6cf
Use string as input parameters
summer-ji-eng Nov 10, 2020
e2f99ab
remove unused dep
summer-ji-eng Nov 10, 2020
e2d2a40
move utils to composer/samplecode
summer-ji-eng Nov 11, 2020
875794f
Merge branch 'sample_code_formatter' of github.com:googleapis/gapic-g…
summer-ji-eng Nov 11, 2020
40977cf
remove utils files
summer-ji-eng Nov 11, 2020
ad842eb
revert BUILD in test
summer-ji-eng Nov 11, 2020
4426dd2
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 12, 2020
2cfa86f
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 12, 2020
222c910
Add comment and rephrase static string
summer-ji-eng Nov 13, 2020
7ca32d8
simplify the wrapper
summer-ji-eng Nov 13, 2020
4f91c12
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 13, 2020
ef1a81d
Merge branch 'master' into sample_code_formatter
summer-ji-eng Nov 13, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ java_library(
deps = [
"//src/main/java/com/google/api/generator/engine/ast",
"@com_google_guava_guava//jar",
"@google_java_format_all_deps//jar",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2020 Google LLC
//
// Licensed 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 com.google.api.generator.gapic.utils;

import com.google.common.annotations.VisibleForTesting;
import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;

public final class SampleCodeJavaFormatter {

private SampleCodeJavaFormatter() {}

private static final Formatter FORMATTER = new Formatter();
private static final String RIGHT_BRACE = "}";
private static final String LEFT_BRACE = "{";
private static final String NEWLINE = "\n";

private static final String FAKE_CLASS_TITLE =
String.format("public class FakeClass %s%s", LEFT_BRACE, NEWLINE);
private static final String FAKE_METHOD_TITLE =
String.format("void fakeMethod() %s%s", LEFT_BRACE, NEWLINE);
private static final String FAKE_METHOD_CLOSE = String.format("%s%s", RIGHT_BRACE, NEWLINE);
private static final String FAKE_CLASS_CLOSE = String.format("%s", RIGHT_BRACE);

/**
* This method is used to format sample code by utilizing google-java-format to format the Java
* source code.
*
* @param sampleCode A string is composed by statements.
* @return String Formatted sample code string based on google java style.
*/
public static String format(String sampleCode) {
final StringBuffer buffer = new StringBuffer();
buffer.append(FAKE_CLASS_TITLE);
buffer.append(FAKE_METHOD_TITLE);
buffer.append(sampleCode);
buffer.append(FAKE_METHOD_CLOSE);
buffer.append(FAKE_CLASS_CLOSE);

String formattedString = null;
try {
formattedString = FORMATTER.formatSource(buffer.toString());
} catch (FormatterException e) {
throw new FormatException(
String.format("The sample code should be string where is composed by statements; %s", e));
}
return formattedString
.replaceAll("^([^\n]*\n){2}|([^\n]*\n){2}$", "")
.replaceAll("(?m)^ {4}", "")
.trim();
}

@VisibleForTesting
protected static class FormatException extends RuntimeException {
public FormatException(String errorMessage) {
super(errorMessage);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package(default_visibility = ["//visibility:public"])

TESTS = [
"JavaStyleTest",
"SampleCodeJavaFormatterTest"
]

filegroup(
Expand All @@ -16,6 +17,8 @@ filegroup(
srcs = ["{0}.java".format(test_name)],
test_class = "com.google.api.generator.gapic.utils.{0}".format(test_name),
deps = [
"//src/main/java/com/google/api/generator/engine/ast",
"//src/main/java/com/google/api/generator/engine/writer",
"//src/main/java/com/google/api/generator/gapic/utils",
"@com_google_truth_truth//jar",
"@junit_junit//jar",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright 2020 Google LLC
//
// Licensed 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 com.google.api.generator.gapic.utils;

import static junit.framework.TestCase.assertEquals;

import com.google.api.generator.engine.ast.AssignmentExpr;
import com.google.api.generator.engine.ast.Expr;
import com.google.api.generator.engine.ast.ExprStatement;
import com.google.api.generator.engine.ast.MethodInvocationExpr;
import com.google.api.generator.engine.ast.PrimitiveValue;
import com.google.api.generator.engine.ast.Statement;
import com.google.api.generator.engine.ast.TryCatchStatement;
import com.google.api.generator.engine.ast.TypeNode;
import com.google.api.generator.engine.ast.Value;
import com.google.api.generator.engine.ast.ValueExpr;
import com.google.api.generator.engine.ast.VaporReference;
import com.google.api.generator.engine.ast.Variable;
import com.google.api.generator.engine.ast.VariableExpr;
import com.google.api.generator.engine.writer.JavaWriterVisitor;
import com.google.api.generator.gapic.utils.SampleCodeJavaFormatter.FormatException;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;

public class SampleCodeJavaFormatterTest {

@Test
public void validFormatSampleCode_tryCatchStatement() {
List<Statement> statements = Arrays.asList(createTryCatchSampleCode());
String result = SampleCodeJavaFormatter.format(writeStatements(statements));
String expected =
String.format(createLines(3), "try (boolean condition = false) {\n", " int x = 3;\n", "}");
assertEquals(expected, result);
}

@Test
public void validFormatSampleCode_longLineStatement() {
TypeNode type =
TypeNode.withReference(
VaporReference.builder()
.setPakkage("com.google.pubsub.v1")
.setName("SubscriptionAdminSettings")
.build());
VariableExpr varDclExpr = createVariableDeclExpr("subscriptionAdminSettings", type);
VariableExpr varExpr = createVariableExpr("SubscriptionAdminSettings", type);
MethodInvocationExpr firstMethodExpr =
MethodInvocationExpr.builder()
.setMethodName("newBuilder")
.setExprReferenceExpr(varExpr)
.build();
MethodInvocationExpr secondMethodExpr =
MethodInvocationExpr.builder()
.setMethodName("setEndpoint")
.setExprReferenceExpr(firstMethodExpr)
.setArguments(Arrays.asList(createVariableExpr("myEndpoint", TypeNode.STRING)))
.build();
MethodInvocationExpr methodExpr =
MethodInvocationExpr.builder()
.setMethodName("build")
.setExprReferenceExpr(secondMethodExpr)
.setReturnType(type)
.build();
List<Statement> statements =
Arrays.asList(
ExprStatement.withExpr(
AssignmentExpr.builder()
.setVariableExpr(varDclExpr)
.setValueExpr(methodExpr)
.build()));
String result = SampleCodeJavaFormatter.format(writeStatements(statements));
String expected =
String.format(
createLines(2),
"SubscriptionAdminSettings subscriptionAdminSettings =\n",
" SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();");
assertEquals(expected, result);
}

@Test(expected = FormatException.class)
public void invalidFormatSampleCode_nonStatement() {
SampleCodeJavaFormatter.format("abc");
}

/** =============================== HELPERS =============================== */
private static String createLines(int numLines) {
return new String(new char[numLines]).replace("\0", "%s");
}

private static Statement createTryCatchSampleCode() {
TryCatchStatement tryCatch =
TryCatchStatement.builder()
.setTryResourceExpr(createAssignmentExpr("condition", "false", TypeNode.BOOLEAN))
.setTryBody(
Arrays.asList(ExprStatement.withExpr(createAssignmentExpr("x", "3", TypeNode.INT))))
.setIsSampleCode(true)
.build();
return tryCatch;
}

private static AssignmentExpr createAssignmentExpr(
String variableName, String value, TypeNode type) {
VariableExpr variableExpr = createVariableDeclExpr(variableName, type);
Value val = PrimitiveValue.builder().setType(type).setValue(value).build();
Expr valueExpr = ValueExpr.builder().setValue(val).build();
return AssignmentExpr.builder().setVariableExpr(variableExpr).setValueExpr(valueExpr).build();
}

private static VariableExpr createVariableDeclExpr(String variableName, TypeNode type) {
return createVariableExpr(variableName, type, true);
}

private static VariableExpr createVariableExpr(String variableName, TypeNode type) {
return createVariableExpr(variableName, type, false);
}

private static VariableExpr createVariableExpr(
String variableName, TypeNode type, boolean isDecl) {
return VariableExpr.builder()
.setVariable(createVariable(variableName, type))
.setIsDecl(isDecl)
.build();
}

private static Variable createVariable(String variableName, TypeNode type) {
return Variable.builder().setName(variableName).setType(type).build();
}

private static String writeStatements(List<Statement> statements) {
JavaWriterVisitor javaWriterVisitor = new JavaWriterVisitor();
for (Statement statement : statements) {
statement.accept(javaWriterVisitor);
}
return javaWriterVisitor.write();
}
}