Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
@@ -0,0 +1,18 @@
load("@rules_java//java:defs.bzl", "java_library")

package(default_visibility = ["//visibility:public"])

filegroup(
name = "samplecode_files",
srcs = glob(["*.java"]),
)

java_library(
name = "samplecode",
srcs = [
":samplecode_files",
],
deps = [
"@google_java_format_all_deps//jar",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// 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.composer.samplecode;

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 FAKE_CLASS_TITLE = "public class FakeClass { void fakeMethod() {";
private static final String FAKE_CLASS_CLOSE = "}}";

/**
* This method is used to format sample code string.
*
* @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();
// Wrap the sample code inside a class for composing a valid Java source code.
// Because we utilized google-java-format to reformat the codes.
buffer.append(FAKE_CLASS_TITLE);
buffer.append(sampleCode);
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));
}
// Extract formatted sample code by
// 1. Removing the first and last two lines.
// 2. Delete the first 4 space for each line.
// 3. Trim the last new empty line.
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 @@ -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,25 @@
load("@rules_java//java:defs.bzl", "java_test")

package(default_visibility = ["//visibility:public"])

TESTS = [
"SampleCodeJavaFormatterTest",
]

filegroup(
name = "samplecode_files",
srcs = ["{0}.java".format(f) for f in TESTS],
)

[java_test(
name = test_name,
srcs = ["{0}.java".format(test_name)],
test_class = "com.google.api.generator.gapic.composer.samplecode.{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/composer/samplecode",
"@com_google_truth_truth//jar",
"@junit_junit//jar",
],
) for test_name in TESTS]
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// 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.composer.samplecode;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertThrows;

import com.google.api.generator.gapic.composer.samplecode.SampleCodeJavaFormatter;
import com.google.api.generator.gapic.composer.samplecode.SampleCodeJavaFormatter.FormatException;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;

public class SampleCodeJavaFormatterTest {

@Test
public void validFormatSampleCode_tryCatchStatement() {
String samplecode = String.format(createLines(3),
"try(boolean condition = false){",
"int x = 3;",
"}");
String result = SampleCodeJavaFormatter.format(samplecode);
String expected =
String.format(createLines(3), "try (boolean condition = false) {\n", " int x = 3;\n", "}");
assertEquals(expected, result);
}

@Test
public void validFormatSampleCode_longLineStatement() {
String sampleCode =
"SubscriptionAdminSettings subscriptionAdminSettings = "
+ "SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();";
String result = SampleCodeJavaFormatter.format(sampleCode);
String expected =
String.format(
createLines(2),
"SubscriptionAdminSettings subscriptionAdminSettings =\n",
" SubscriptionAdminSettings.newBuilder().setEndpoint(myEndpoint).build();");
assertEquals(expected, result);
}

@Test
public void validFormatSampleCode_longChainMethod() {
String sampleCode = "echoSettingsBuilder.echoSettings().setRetrySettings(echoSettingsBuilder.echoSettings().getRetrySettings().toBuilder().setTotalTimeout(Duration.ofSeconds(30)).build());";
String result = SampleCodeJavaFormatter.format(sampleCode);
String expected =
String.format(
createLines(9),
"echoSettingsBuilder\n",
" .echoSettings()\n",
" .setRetrySettings(\n",
" echoSettingsBuilder\n",
" .echoSettings()\n",
" .getRetrySettings()\n",
" .toBuilder()\n",
" .setTotalTimeout(Duration.ofSeconds(30))\n",
" .build());");
assertEquals(expected, result);
}

@Test
public void invalidFormatSampleCode_nonStatement() {
assertThrows(
FormatException.class,
() -> {
SampleCodeJavaFormatter.format("abc");
});
}

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