-
Notifications
You must be signed in to change notification settings - Fork 69
[composer][SampleCode]Utils function formatter for Sample Code #471
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
Merged
Merged
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 2bf804e
Add unit test for long line
summer-ji-eng b0c6b47
Implement formatter for code snippet
summer-ji-eng 94bd9ed
Add license and comment
summer-ji-eng 209ec9d
Merge branch 'master' into sample_code_formatter
summer-ji-eng 7176a85
Use string as input parameters
summer-ji-eng 62da37b
remove unused dep
summer-ji-eng c9213eb
Merge branch 'master' into sample_code_formatter
summer-ji-eng 07d9d21
draft version
summer-ji-eng 55c7604
Add unit test for long line
summer-ji-eng 9f1b49d
Implement formatter for code snippet
summer-ji-eng 3126e5f
Add license and comment
summer-ji-eng 308e6cf
Use string as input parameters
summer-ji-eng e2f99ab
remove unused dep
summer-ji-eng e2d2a40
move utils to composer/samplecode
summer-ji-eng 875794f
Merge branch 'sample_code_formatter' of github.com:googleapis/gapic-g…
summer-ji-eng 40977cf
remove utils files
summer-ji-eng ad842eb
revert BUILD in test
summer-ji-eng 4426dd2
Merge branch 'master' into sample_code_formatter
summer-ji-eng 2cfa86f
Merge branch 'master' into sample_code_formatter
summer-ji-eng 222c910
Add comment and rephrase static string
summer-ji-eng 7ca32d8
simplify the wrapper
summer-ji-eng 4f91c12
Merge branch 'master' into sample_code_formatter
summer-ji-eng ef1a81d
Merge branch 'master' into sample_code_formatter
summer-ji-eng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
src/main/java/com/google/api/generator/gapic/utils/SampleCodeJavaFormatter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}$", "") | ||
summer-ji-eng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| .replaceAll("(?m)^ {4}", "") | ||
| .trim(); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
miraleung marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| protected static class FormatException extends RuntimeException { | ||
| public FormatException(String errorMessage) { | ||
| super(errorMessage); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
src/test/java/com/google/api/generator/gapic/utils/SampleCodeJavaFormatterTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() { | ||
summer-ji-eng marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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(); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.