diff --git a/.gitignore b/.gitignore index acb22fef47..a0f2b0e98b 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,6 @@ out/ .gradle build generated -gradle gradlew gradlew.bat diff --git a/build.gradle.kts b/build.gradle.kts index 0a90225df6..4ad490b857 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,6 +1,8 @@ import com.diffplug.gradle.spotless.SpotlessExtension +import com.diffplug.spotless.LineEnding import com.vanniktech.maven.publish.MavenPublishBaseExtension import com.vanniktech.maven.publish.SonatypeHost +import kotlinx.validation.ApiValidationExtension import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED import org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED @@ -10,7 +12,6 @@ import org.jetbrains.dokka.gradle.DokkaTask import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -import kotlinx.validation.ApiValidationExtension buildscript { dependencies { @@ -56,36 +57,30 @@ allprojects { } subprojects { - apply(plugin = "com.diffplug.spotless") - configure { - val licenseHeaderFile = rootProject.file("gradle/license-header.txt") - kotlin { - target("**/*.kt") - ktlint(libs.versions.ktlint.get()).editorConfigOverride( - mapOf("ktlint_standard_filename" to "disabled"), - ) - trimTrailingWhitespace() - endWithNewline() - toggleOffOn() - // We cannot use it because the licensing job happens before. The header will be replaced and - // spotless will throw. We have to manually exclude stuff for now. - // See https://github.com/diffplug/spotless/discussions/1738 - toggleOffOnRegex("""^(// Code generated by Wire protocol buffer compiler[\s\S]*)$""") - - licenseHeaderFile(licenseHeaderFile) - } - java { - target("**/*.java") - googleJavaFormat(libs.googleJavaFormat.get().version) - trimTrailingWhitespace() - endWithNewline() - toggleOffOn() - // We cannot use it because the licensing job happens before. The header will be replaced and - // spotless will throw. We have to manually exclude stuff for now. - // See https://github.com/diffplug/spotless/discussions/1738 - // toggleOffOnRegex("""^(// Code generated by Wire protocol buffer compiler[\s\S]*)$""") - - licenseHeaderFile(licenseHeaderFile) + if (name != "wire-golden-files") { + apply(plugin = "com.diffplug.spotless") + configure { + val licenseHeaderFile = rootProject.file("gradle/license-header.txt") + kotlin { + target("**/*.kt") + ktlint(libs.versions.ktlint.get()).editorConfigOverride( + mapOf("ktlint_standard_filename" to "disabled"), + ) + trimTrailingWhitespace() + endWithNewline() + toggleOffOn() + lineEndings = LineEnding.UNIX + licenseHeaderFile(licenseHeaderFile) + } + java { + target("**/*.java") + googleJavaFormat(libs.googleJavaFormat.get().version) + trimTrailingWhitespace() + endWithNewline() + toggleOffOn() + lineEndings = LineEnding.UNIX + licenseHeaderFile(licenseHeaderFile) + } } } diff --git a/gradle/license-header.txt b/gradle/license-header.txt new file mode 100644 index 0000000000..b2a05698ab --- /dev/null +++ b/gradle/license-header.txt @@ -0,0 +1,15 @@ +/* + * Copyright (C) $YEAR Square, Inc. + * + * 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 + * + * https://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. + */ diff --git a/samples/android-app-java-sample/src/main/java/com/squareup/wire/android/app/java/MainActivity.java b/samples/android-app-java-sample/src/main/java/com/squareup/wire/android/app/java/MainActivity.java index 080659dfee..4d1f7d409e 100644 --- a/samples/android-app-java-sample/src/main/java/com/squareup/wire/android/app/java/MainActivity.java +++ b/samples/android-app-java-sample/src/main/java/com/squareup/wire/android/app/java/MainActivity.java @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -15,10 +15,9 @@ */ package com.squareup.wire.android.app.java; +import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; -import android.os.Bundle; - public class MainActivity extends AppCompatActivity { diff --git a/samples/android-app-kotlin-sample/src/main/java/com/squareup/wire/android/app/kotlin/MainActivity.kt b/samples/android-app-kotlin-sample/src/main/java/com/squareup/wire/android/app/kotlin/MainActivity.kt index 41b093f4c8..2910c9b279 100644 --- a/samples/android-app-kotlin-sample/src/main/java/com/squareup/wire/android/app/kotlin/MainActivity.kt +++ b/samples/android-app-kotlin-sample/src/main/java/com/squareup/wire/android/app/kotlin/MainActivity.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, diff --git a/samples/android-app-variants-sample/src/main/java/com/squareup/wire/android/app/variants/MainActivity.kt b/samples/android-app-variants-sample/src/main/java/com/squareup/wire/android/app/variants/MainActivity.kt index 5c7e009e68..1b232623fa 100644 --- a/samples/android-app-variants-sample/src/main/java/com/squareup/wire/android/app/variants/MainActivity.kt +++ b/samples/android-app-variants-sample/src/main/java/com/squareup/wire/android/app/variants/MainActivity.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.android.app.variants import android.os.Bundle diff --git a/samples/android-app-variants-sample/src/test/java/com/squareup/wire/android/app/variants/CommonUnitTest.kt b/samples/android-app-variants-sample/src/test/java/com/squareup/wire/android/app/variants/CommonUnitTest.kt index 955da2b043..deeb5d8321 100644 --- a/samples/android-app-variants-sample/src/test/java/com/squareup/wire/android/app/variants/CommonUnitTest.kt +++ b/samples/android-app-variants-sample/src/test/java/com/squareup/wire/android/app/variants/CommonUnitTest.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.android.app.variants import org.junit.Test diff --git a/samples/android-app-variants-sample/src/testDebug/java/com/squareup/wire/android/app/variants/DebugUnitTest.kt b/samples/android-app-variants-sample/src/testDebug/java/com/squareup/wire/android/app/variants/DebugUnitTest.kt index d9af3e72f3..21909db589 100644 --- a/samples/android-app-variants-sample/src/testDebug/java/com/squareup/wire/android/app/variants/DebugUnitTest.kt +++ b/samples/android-app-variants-sample/src/testDebug/java/com/squareup/wire/android/app/variants/DebugUnitTest.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.android.app.variants import org.junit.Assert.fail diff --git a/samples/android-app-variants-sample/src/testRelease/java/com/squareup/wire/android/app/variants/ReleaseUnitTest.kt b/samples/android-app-variants-sample/src/testRelease/java/com/squareup/wire/android/app/variants/ReleaseUnitTest.kt index 6315a22664..ba6ebd4b07 100644 --- a/samples/android-app-variants-sample/src/testRelease/java/com/squareup/wire/android/app/variants/ReleaseUnitTest.kt +++ b/samples/android-app-variants-sample/src/testRelease/java/com/squareup/wire/android/app/variants/ReleaseUnitTest.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.android.app.variants import org.junit.Assert.fail diff --git a/samples/android-lib-java-sample/src/main/java/com/squareup/wire/android/lib/java/SomeObject.java b/samples/android-lib-java-sample/src/main/java/com/squareup/wire/android/lib/java/SomeObject.java index 1ab8d3a322..1bc7f605e1 100644 --- a/samples/android-lib-java-sample/src/main/java/com/squareup/wire/android/lib/java/SomeObject.java +++ b/samples/android-lib-java-sample/src/main/java/com/squareup/wire/android/lib/java/SomeObject.java @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, diff --git a/samples/android-lib-kotlin-sample/src/main/java/com/squareup/wire/android/lib/kotlin/SomeObject.kt b/samples/android-lib-kotlin-sample/src/main/java/com/squareup/wire/android/lib/kotlin/SomeObject.kt index 3e31e2e12e..dd2c1c195c 100644 --- a/samples/android-lib-kotlin-sample/src/main/java/com/squareup/wire/android/lib/kotlin/SomeObject.kt +++ b/samples/android-lib-kotlin-sample/src/main/java/com/squareup/wire/android/lib/kotlin/SomeObject.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, diff --git a/samples/js/src/main/kotlin/Main.kt b/samples/js/src/main/kotlin/Main.kt index 30714c04f0..a56e922d9a 100644 --- a/samples/js/src/main/kotlin/Main.kt +++ b/samples/js/src/main/kotlin/Main.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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. + */ import human.Person fun main() { diff --git a/samples/native/src/nativeMain/kotlin/Main.kt b/samples/native/src/nativeMain/kotlin/Main.kt index 30714c04f0..a56e922d9a 100644 --- a/samples/native/src/nativeMain/kotlin/Main.kt +++ b/samples/native/src/nativeMain/kotlin/Main.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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. + */ import human.Person fun main() { diff --git a/samples/simple-sample/src/main/java/com/squareup/dinosaurs/Sample.java b/samples/simple-sample/src/main/java/com/squareup/dinosaurs/Sample.java index eebeb3217a..496b07cc67 100644 --- a/samples/simple-sample/src/main/java/com/squareup/dinosaurs/Sample.java +++ b/samples/simple-sample/src/main/java/com/squareup/dinosaurs/Sample.java @@ -1,11 +1,11 @@ /* - * Copyright 2015 Square Inc. + * Copyright (C) 2015 Square, Inc. * * 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 + * https://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, @@ -23,24 +23,27 @@ public final class Sample { public void run() throws IOException { // Create an immutable value object with the Builder API. - Dinosaur stegosaurus = new Dinosaur.Builder() - .name("Stegosaurus") - .period(Period.JURASSIC) - .length_meters(9.0) - .mass_kilograms(5_000.0) - .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) - .build(); + Dinosaur stegosaurus = + new Dinosaur.Builder() + .name("Stegosaurus") + .period(Period.JURASSIC) + .length_meters(9.0) + .mass_kilograms(5_000.0) + .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) + .build(); // Encode that value to bytes, and print that as base64. byte[] stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus); System.out.println(ByteString.of(stegosaurusEncoded).base64()); // Decode base64 bytes, and decode those bytes as a dinosaur. - ByteString tyrannosaurusEncoded = ByteString.decodeBase64("Cg1UeXJhbm5vc2F1cnVzEmhodHRwOi8vdmln" - + "bmV0dGUxLndpa2lhLm5vY29va2llLm5ldC9qdXJhc3NpY3BhcmsvaW1hZ2VzLzYvNmEvTGVnbzUuanBnL3Jldmlz" - + "aW9uL2xhdGVzdD9jYj0yMDE1MDMxOTAxMTIyMRJtaHR0cDovL3ZpZ25ldHRlMy53aWtpYS5ub2Nvb2tpZS5uZXQv" - + "anVyYXNzaWNwYXJrL2ltYWdlcy81LzUwL1JleHlfcHJlcGFyaW5nX2Zvcl9iYXR0bGVfd2l0aF9JbmRvbWludXNf" - + "cmV4LmpwZxmamZmZmZkoQCEAAAAAAJC6QCgB"); + ByteString tyrannosaurusEncoded = + ByteString.decodeBase64( + "Cg1UeXJhbm5vc2F1cnVzEmhodHRwOi8vdmln" + + "bmV0dGUxLndpa2lhLm5vY29va2llLm5ldC9qdXJhc3NpY3BhcmsvaW1hZ2VzLzYvNmEvTGVnbzUuanBnL3Jldmlz" + + "aW9uL2xhdGVzdD9jYj0yMDE1MDMxOTAxMTIyMRJtaHR0cDovL3ZpZ25ldHRlMy53aWtpYS5ub2Nvb2tpZS5uZXQv" + + "anVyYXNzaWNwYXJrL2ltYWdlcy81LzUwL1JleHlfcHJlcGFyaW5nX2Zvcl9iYXR0bGVfd2l0aF9JbmRvbWludXNf" + + "cmV4LmpwZxmamZmZmZkoQCEAAAAAAJC6QCgB"); Dinosaur tyrannosaurus = Dinosaur.ADAPTER.decode(tyrannosaurusEncoded.toByteArray()); // Print both of our dinosaurs. diff --git a/samples/wire-codegen-sample/src/main/java/com/squareup/wire/sample/ServiceGenerator.java b/samples/wire-codegen-sample/src/main/java/com/squareup/wire/sample/ServiceGenerator.java index 3511e8fd9c..7b0fa5d144 100644 --- a/samples/wire-codegen-sample/src/main/java/com/squareup/wire/sample/ServiceGenerator.java +++ b/samples/wire-codegen-sample/src/main/java/com/squareup/wire/sample/ServiceGenerator.java @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,6 +15,9 @@ */ package com.squareup.wire.sample; +import static javax.lang.model.element.Modifier.ABSTRACT; +import static javax.lang.model.element.Modifier.PUBLIC; + import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; @@ -24,9 +27,6 @@ import com.squareup.wire.schema.Rpc; import com.squareup.wire.schema.Service; -import static javax.lang.model.element.Modifier.ABSTRACT; -import static javax.lang.model.element.Modifier.PUBLIC; - final class ServiceGenerator { final JavaGenerator javaGenerator; diff --git a/samples/wire-codegen-sample/src/test/java/com/squareup/wire/sample/ServiceGeneratorTest.kt b/samples/wire-codegen-sample/src/test/java/com/squareup/wire/sample/ServiceGeneratorTest.kt index e431759d4a..f8e43ceb80 100644 --- a/samples/wire-codegen-sample/src/test/java/com/squareup/wire/sample/ServiceGeneratorTest.kt +++ b/samples/wire-codegen-sample/src/test/java/com/squareup/wire/sample/ServiceGeneratorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -21,21 +21,22 @@ import com.squareup.wire.java.JavaGenerator import com.squareup.wire.schema.Location import com.squareup.wire.schema.Schema import com.squareup.wire.schema.SchemaLoader +import java.io.File +import java.io.IOException +import java.nio.file.FileSystems import okio.buffer import okio.sink import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder -import java.io.File -import java.io.IOException -import java.nio.file.FileSystems class ServiceGeneratorTest { @get:Rule var temporaryFolder = TemporaryFolder() - @Test @Throws(IOException::class) + @Test + @Throws(IOException::class) fun service() { val schema = schema( mapOf( @@ -62,8 +63,9 @@ class ServiceGeneratorTest { | rpc FirstRpc (SampleRequest) returns (SampleResponse); | rpc OtherOne (SampleRequest) returns (SampleResponse); |} - |""".trimMargin() - ) + | + """.trimMargin(), + ), ) val service = schema.getService("squareup.wire.sample.SampleApi") val javaGenerator = JavaGenerator.get(schema) @@ -85,7 +87,8 @@ class ServiceGeneratorTest { | | SampleResponse OtherOne(SampleRequest request); |} - |""".trimMargin() + | + """.trimMargin(), ) } diff --git a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/GrpcClientProvider.kt b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/GrpcClientProvider.kt index eba97993a2..0135e974a8 100644 --- a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/GrpcClientProvider.kt +++ b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/GrpcClientProvider.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -16,10 +16,6 @@ package com.squareup.wire.whiteboard import com.squareup.wire.GrpcClient -import okhttp3.OkHttpClient -import okhttp3.Protocol.HTTP_1_1 -import okhttp3.Protocol.HTTP_2 -import okio.Buffer import java.io.IOException import java.io.InputStream import java.security.GeneralSecurityException @@ -32,6 +28,10 @@ import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager +import okhttp3.OkHttpClient +import okhttp3.Protocol.HTTP_1_1 +import okhttp3.Protocol.HTTP_2 +import okio.Buffer object GrpcClientProvider { private val okHttpClient = OkHttpClient.Builder() @@ -55,7 +55,7 @@ object GrpcClientProvider { val sslSocketFactory: SSLSocketFactory try { trustManager = trustManagerForCertificates( - trustedCertificatesInputStream() + trustedCertificatesInputStream(), ) val sslContext = SSLContext.getInstance("TLS") sslContext.init(null, arrayOf(trustManager), null) @@ -109,17 +109,17 @@ object GrpcClientProvider { // Use it to build an X509 trust manager. val keyManagerFactory = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm() + KeyManagerFactory.getDefaultAlgorithm(), ) keyManagerFactory.init(keyStore, password) val trustManagerFactory = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm() + TrustManagerFactory.getDefaultAlgorithm(), ) trustManagerFactory.init(keyStore) val trustManagers = trustManagerFactory.trustManagers if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) { throw IllegalStateException( - "Unexpected default trust managers:" + Arrays.toString(trustManagers) + "Unexpected default trust managers:" + Arrays.toString(trustManagers), ) } return trustManagers[0] as X509TrustManager diff --git a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt index d6b425f468..0c2515ff3c 100644 --- a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt +++ b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -24,6 +24,7 @@ import com.squareup.wire.whiteboard.WhiteboardUpdate.InitialiseBoard import com.squareup.wire.whiteboard.WhiteboardUpdate.UpdatePoints import com.squareup.wire.whiteboard.ui.MainContentView import com.squareup.wire.whiteboard.ui.WhiteboardView +import java.io.IOException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -31,7 +32,6 @@ import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import java.io.IOException class MainActivity : ComponentActivity(), OnBoardEventListener { private lateinit var sendCommandChannel: SendChannel @@ -60,7 +60,7 @@ class MainActivity : ComponentActivity(), OnBoardEventListener { withContext(Dispatchers.Main) { when { update.initialise_board != null -> initialiseBoard( - update.initialise_board as InitialiseBoard + update.initialise_board as InitialiseBoard, ) update.update_points != null -> updatePoints(update.update_points as UpdatePoints) diff --git a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/MainContentView.kt b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/MainContentView.kt index 8521b444dd..1fec2e30eb 100644 --- a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/MainContentView.kt +++ b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/MainContentView.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -50,7 +50,7 @@ class MainContentView(context: Context) : ContourLayout(context) { ) button.layoutBy( x = centerHorizontallyTo { parent.centerX() }.widthOf(AtMost) { parent.width() - 48.dip }, - y = bottomTo { parent.bottom() - 24.dip } + y = bottomTo { parent.bottom() - 24.dip }, ) } } diff --git a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/WhiteboardView.kt b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/WhiteboardView.kt index 70a59f319a..8a96664711 100644 --- a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/WhiteboardView.kt +++ b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/ui/WhiteboardView.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -55,7 +55,7 @@ class WhiteboardView( realY - realHeight / 2f, realX + realWidth / 2f - 1, realY + realHeight / 2f - 1, - Paint().apply { color = point.color } + Paint().apply { color = point.color }, ) } } @@ -64,7 +64,8 @@ class WhiteboardView( override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN, - MotionEvent.ACTION_MOVE -> { + MotionEvent.ACTION_MOVE, + -> { val (abstractX, abstractY) = convertToAbstract(event.x, event.y) onBoardEventListener!!.onPoint(Point(abstractX, abstractY, color)) } @@ -76,18 +77,18 @@ class WhiteboardView( private fun convertToReal( x: Int, - y: Int + y: Int, ) = Pair( x * width / abstractWidth, - y * height / abstractHeight + y * height / abstractHeight, ) private fun convertToAbstract( x: Float, - y: Float + y: Float, ) = Pair( (x / width * abstractWidth).roundToInt(), - (y / height * abstractHeight).roundToInt() + (y / height * abstractHeight).roundToInt(), ) private fun Canvas.showEmptyView() { @@ -103,7 +104,7 @@ class WhiteboardView( text, (centerX - (paint.measureText(text) / 2).toInt()).toFloat(), (centerY - (paint.descent() + paint.ascent()) / 2).toInt().toFloat(), - paint + paint, ) } } diff --git a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardCompatImpl.kt b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardCompatImpl.kt index 6b388b6504..1d78d4238e 100644 --- a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardCompatImpl.kt +++ b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardCompatImpl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -24,7 +24,7 @@ class WhiteboardCompatImpl() : WhiteboardWireGrpc.WhiteboardImplBase() { override fun Whiteboard(response: StreamObserver): StreamObserver { return WhiteboardWireGrpc.BindableAdapter( Whiteboard = { WhiteboardCompat() }, - streamExecutor = Executors.newSingleThreadExecutor() + streamExecutor = Executors.newSingleThreadExecutor(), ) .Whiteboard(response) } @@ -33,14 +33,14 @@ class WhiteboardCompatImpl() : WhiteboardWireGrpc.WhiteboardImplBase() { class WhiteboardCompat : WhiteboardWhiteboardBlockingServer { override fun Whiteboard( request: MessageSource, - response: MessageSink + response: MessageSink, ) { response.write( WhiteboardUpdate( update_points = WhiteboardUpdate.UpdatePoints( - listOf(Point(0, 0, 0)) - ) - ) + listOf(Point(0, 0, 0)), + ), + ), ) } } diff --git a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardImpl.kt b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardImpl.kt index 83566dc3a1..bf8bdc114f 100644 --- a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardImpl.kt +++ b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardImpl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -25,10 +25,10 @@ class WhiteboardImpl : WhiteboardWireGrpc.WhiteboardImplBase() { WhiteboardUpdate( update_points = WhiteboardUpdate.UpdatePoints( listOf( - Point(0, 0, 0) - ) - ) - ) + Point(0, 0, 0), + ), + ), + ), ) } diff --git a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardServer.kt b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardServer.kt index 4c97b3fba7..741b3aebac 100644 --- a/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardServer.kt +++ b/samples/wire-grpc-sample/server-plain/src/main/java/com/squareup/wire/whiteboard/WhiteboardServer.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/Grpc.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/Grpc.kt index 64845bafcf..8f13fe85bb 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/Grpc.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/Grpc.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/MiskGrpcServer.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/MiskGrpcServer.kt index 3ef189dc00..f9af920663 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/MiskGrpcServer.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/MiskGrpcServer.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -32,6 +32,6 @@ fun main(args: Array) { MiskWebModule(config.web), WhiteboardGrpcModule(), ConfigModule.create("whiteboard", config), - EnvironmentModule(environment) + EnvironmentModule(environment), ).run(args) } diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardConfig.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardConfig.kt index 41d2f99772..127a82f853 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardConfig.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardConfig.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -19,5 +19,5 @@ import misk.config.Config import misk.web.WebConfig data class WhiteboardConfig( - val web: WebConfig + val web: WebConfig, ) : Config diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt index 46a756acfb..56f0d79336 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -19,8 +19,8 @@ import com.squareup.wire.MessageSink import com.squareup.wire.MessageSource import com.squareup.wire.whiteboard.WhiteboardUpdate.InitialiseBoard import com.squareup.wire.whiteboard.WhiteboardUpdate.UpdatePoints -import misk.web.actions.WebAction import javax.inject.Singleton +import misk.web.actions.WebAction @Singleton class WhiteboardGrpcAction : WebAction, WhiteboardWhiteboardBlockingServer { @@ -29,7 +29,7 @@ class WhiteboardGrpcAction : WebAction, WhiteboardWhiteboardBlockingServer { override fun Whiteboard( request: MessageSource, - response: MessageSink + response: MessageSink, ) { val client = Client(request, response) clients += client @@ -38,14 +38,14 @@ class WhiteboardGrpcAction : WebAction, WhiteboardWhiteboardBlockingServer { inner class Client( private val commands: MessageSource, - private val updates: MessageSink + private val updates: MessageSink, ) { fun process() { updates.use { val initialiseBoard = InitialiseBoard( BOARD_WIDTH, BOARD_HEIGHT, - COLORS[clients.indexOf(this) % COLORS.size] + COLORS[clients.indexOf(this) % COLORS.size], ) updates.write(WhiteboardUpdate(initialise_board = initialiseBoard)) updates.write(WhiteboardUpdate(update_points = UpdatePoints(points))) @@ -75,7 +75,7 @@ class WhiteboardGrpcAction : WebAction, WhiteboardWhiteboardBlockingServer { 0xff00c8fa.toInt(), // Blue 0xfff46e38.toInt(), // Red 0xff0bb634.toInt(), // Green - 0xff333333.toInt() // Black + 0xff333333.toInt(), // Black ) } } diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcModule.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcModule.kt index 583d3d678d..27eb2fca4a 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcModule.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcModule.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/AllTypesBenchmark.kt b/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/AllTypesBenchmark.kt index 7660dcefb9..378e2c0259 100644 --- a/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/AllTypesBenchmark.kt +++ b/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/AllTypesBenchmark.kt @@ -1,11 +1,11 @@ /* - * Copyright (C) 2022 Block, Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -19,6 +19,7 @@ import com.squareup.moshi.Moshi import com.squareup.wire.ProtoWriter import com.squareup.wire.ReverseProtoWriter import com.squareup.wire.WireJsonAdapterFactory +import java.util.concurrent.TimeUnit import okio.Buffer import okio.BufferedSource import okio.FileSystem @@ -33,7 +34,6 @@ import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.Setup import org.openjdk.jmh.annotations.State import org.openjdk.jmh.annotations.Warmup -import java.util.concurrent.TimeUnit import squareup.wire.benchmarks.proto2.AllTypes as Proto2Wire import squareup.wire.benchmarks.proto2.AllTypesProto2.AllTypes as Proto2Protobuf import squareup.wire.benchmarks.proto3.AllTypes as Proto3Wire diff --git a/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/SimpleMessageBenchmark.java b/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/SimpleMessageBenchmark.java index f3323bff57..3127947c5f 100644 --- a/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/SimpleMessageBenchmark.java +++ b/wire-benchmarks/src/jmh/java/com/squareup/wire/benchmarks/SimpleMessageBenchmark.java @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,6 +15,9 @@ */ package com.squareup.wire.benchmarks; +import static java.util.concurrent.TimeUnit.MICROSECONDS; +import static org.openjdk.jmh.annotations.Mode.SampleTime; + import com.squareup.wire.ProtoWriter; import com.squareup.wire.ReverseProtoWriter; import java.io.File; @@ -36,9 +39,6 @@ import squareup.wire.benchmarks.EmailSearchResponse; import squareup.wire.benchmarks.EmailSearchResponseProto; -import static java.util.concurrent.TimeUnit.MICROSECONDS; -import static org.openjdk.jmh.annotations.Mode.SampleTime; - @Fork(1) @Warmup(iterations = 5, time = 2) @Measurement(iterations = 5, time = 2) @@ -49,45 +49,49 @@ public class SimpleMessageBenchmark { Buffer buffer = new Buffer(); byte[] bytes; - @Setup public void setup() throws IOException { + @Setup + public void setup() throws IOException { // `medium_value.bytes` contains bytes for the message // [squareup.wire.benchmarks.EmailSearchResponse]. File file = new File("src/main/resources/medium_value.bytes"); try (Source fileSource = Okio.source(file); - BufferedSource bufferedFileSource = Okio.buffer(fileSource)) { + BufferedSource bufferedFileSource = Okio.buffer(fileSource)) { bytes = bufferedFileSource.readByteArray(); } } - @Benchmark public void encodeWire3x() throws IOException { + @Benchmark + public void encodeWire3x() throws IOException { ProtoWriter writer = new ProtoWriter(buffer); EmailSearchResponse.ADAPTER.encode(writer, SampleData.newMediumValueWire()); buffer.clear(); } - @Benchmark public void encodeWire4x() throws IOException { + @Benchmark + public void encodeWire4x() throws IOException { ReverseProtoWriter writer = new ReverseProtoWriter(); EmailSearchResponse.ADAPTER.encode(writer, SampleData.newMediumValueWire()); writer.writeTo(buffer); buffer.clear(); } - @Benchmark public void encodeProtobuf() throws IOException { + @Benchmark + public void encodeProtobuf() throws IOException { SampleData.newMediumValueProtobuf().writeTo(buffer.outputStream()); buffer.clear(); } - @Benchmark public void decodeWire() throws IOException { + @Benchmark + public void decodeWire() throws IOException { EmailSearchResponse.ADAPTER.decode(bytes); } - @Benchmark public void decodeProtobuf() throws IOException { + @Benchmark + public void decodeProtobuf() throws IOException { EmailSearchResponseProto.EmailSearchResponse.parseFrom(bytes); } - /** - * Run encode for 10 seconds to capture a profile. - */ + /** Run encode for 10 seconds to capture a profile. */ public static void main(String[] args) throws IOException { long now = System.nanoTime(); long done = now + TimeUnit.SECONDS.toNanos(10L); diff --git a/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt b/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt index 76a5c5bb93..d62d005e9d 100644 --- a/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt +++ b/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.benchmarks import squareup.wire.benchmarks.EmailMessage as EmailMessageWire @@ -45,7 +60,8 @@ object SampleData { |> (519) 555-2233 |> dentist@example.com |> - |""".trimMargin() + | + """.trimMargin() @JvmStatic fun newMediumValueWire(): EmailSearchResponseWire { @@ -54,9 +70,9 @@ object SampleData { results = listOf( EmailThreadWire( subject = subject, - messages = listOf(newEmailMessageWire()) - ) - ) + messages = listOf(newEmailMessageWire()), + ), + ), ) } @@ -65,17 +81,17 @@ object SampleData { sender = newSenderWire(), recipients = listOf(newRecipientWire()), subject = subject, - body = body + body = body, ) fun newSenderWire() = NameAndAddressWire( display_name = senderDisplayName, - email_address = senderEmailAddress + email_address = senderEmailAddress, ) fun newRecipientWire() = NameAndAddressWire( display_name = recipientDisplayName, - email_address = recipientEmailAddress + email_address = recipientEmailAddress, ) @JvmStatic @@ -88,7 +104,7 @@ object SampleData { .apply { subject = SampleData.subject addMessages(newEmailMessageProtobuf()) - }.build() + }.build(), ) }.build() } diff --git a/wire-gradle-plugin-playground/src/main/java/MyListener.java b/wire-gradle-plugin-playground/src/main/java/MyListener.java index c93b793d5c..c7cae0b690 100644 --- a/wire-gradle-plugin-playground/src/main/java/MyListener.java +++ b/wire-gradle-plugin-playground/src/main/java/MyListener.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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. + */ import com.squareup.wire.schema.EmittingRules; import com.squareup.wire.schema.EventListener; import com.squareup.wire.schema.PruningRules; @@ -9,27 +24,33 @@ import org.jetbrains.annotations.NotNull; public class MyListener extends EventListener { - @Override public void runStart(@NotNull WireRun wireRun) { + @Override + public void runStart(@NotNull WireRun wireRun) { super.runStart(wireRun); } - @Override public void runSuccess(@NotNull WireRun wireRun) { + @Override + public void runSuccess(@NotNull WireRun wireRun) { super.runSuccess(wireRun); } - @Override public void runFailed(@NotNull List errors) { + @Override + public void runFailed(@NotNull List errors) { super.runFailed(errors); } - @Override public void loadSchemaStart() { + @Override + public void loadSchemaStart() { super.loadSchemaStart(); } - @Override public void loadSchemaSuccess(@NotNull Schema schema) { + @Override + public void loadSchemaSuccess(@NotNull Schema schema) { super.loadSchemaSuccess(schema); } - @Override public void treeShakeStart(@NotNull Schema schema, @NotNull PruningRules pruningRules) { + @Override + public void treeShakeStart(@NotNull Schema schema, @NotNull PruningRules pruningRules) { super.treeShakeStart(schema, pruningRules); } @@ -48,21 +69,25 @@ public void moveTypesEnd(@NotNull Schema refactoredSchema, @NotNull List, sourceTrees: MutableSet, sourceJars: MutableSet, - name: String + name: String, ) { val protoRootSet = objectFactory.newInstance(ProtoRootSet::class.java) action.execute(protoRootSet) diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt index 0947fa132f..dbc9f7bf6f 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -16,6 +16,10 @@ package com.squareup.wire.gradle import com.squareup.wire.gradle.WireExtension.ProtoRootSet +import java.io.EOFException +import java.io.File +import java.io.RandomAccessFile +import java.net.URI import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency @@ -26,10 +30,6 @@ import org.gradle.api.internal.catalog.DelegatingProjectDependency import org.gradle.api.internal.file.FileOrUriNotationConverter import org.gradle.api.logging.Logger import org.gradle.api.provider.Provider -import java.io.EOFException -import java.io.File -import java.io.RandomAccessFile -import java.net.URI /** * Builds Wire's inputs (expressed as [InputLocation] lists) from Gradle's objects (expressed as @@ -108,12 +108,12 @@ internal class WireInput(var configuration: Configuration) { | include 'relativePath' | } |} - """.trimMargin() + """.trimMargin(), ) } } else if (converted is URI && isURL(converted)) { throw IllegalArgumentException( - "Invalid path string: \"$dependency\". URL dependencies are not allowed." + "Invalid path string: \"$dependency\". URL dependencies are not allowed.", ) } else { // Assume it's a possible external dependency and let Gradle sort it out later. @@ -170,8 +170,8 @@ internal class WireInput(var configuration: Configuration) { InputLocation.get( project = project, base = srcDir.path, - path = relativeTo(srcDir).toString() - ) + path = relativeTo(srcDir).toString(), + ), ) } else if (isZip) { val filters = dependencyFilters.getOrDefault(dependency, listOf()) diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt index 939d2ec699..857ab4cfc5 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -89,12 +89,12 @@ open class KotlinOutput @Inject constructor() : WireOutput() { val rpcCallStyle = RpcCallStyle.values() .singleOrNull { it.toString().equals(rpcCallStyle, ignoreCase = true) } ?: throw IllegalArgumentException( - "Unknown rpcCallStyle $rpcCallStyle. Valid values: ${RpcCallStyle.values().contentToString()}" + "Unknown rpcCallStyle $rpcCallStyle. Valid values: ${RpcCallStyle.values().contentToString()}", ) val rpcRole = RpcRole.values() .singleOrNull { it.toString().equals(rpcRole, ignoreCase = true) } ?: throw IllegalArgumentException( - "Unknown rpcRole $rpcRole. Valid values: ${RpcRole.values().contentToString()}" + "Unknown rpcRole $rpcRole. Valid values: ${RpcRole.values().contentToString()}", ) return KotlinTarget( @@ -127,6 +127,7 @@ open class CustomOutput @Inject constructor() : WireOutput() { var includes: List? = null var excludes: List? = null var exclusive: Boolean = true + /** * Black boxed payload which a caller can set for the custom [SchemaHandler.Factory] to receive. */ diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt index ed959a0c7a..2299e9b0d4 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -23,6 +23,9 @@ import com.squareup.wire.gradle.internal.targetDefaultOutputPath import com.squareup.wire.gradle.kotlin.Source import com.squareup.wire.gradle.kotlin.sourceRoots import com.squareup.wire.schema.newEventListenerFactory +import java.io.File +import java.lang.reflect.Array as JavaArray +import java.util.concurrent.atomic.AtomicBoolean import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.Dependency @@ -37,9 +40,6 @@ import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet import org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -import java.io.File -import java.util.concurrent.atomic.AtomicBoolean -import java.lang.reflect.Array as JavaArray class WirePlugin : Plugin { private val android = AtomicBoolean(false) @@ -149,7 +149,7 @@ class WirePlugin : Plugin { project.relativePath(source.outputDir(project)) } else { output.out!! - } + }, ) } val generatedSourcesDirectories: Set = @@ -259,8 +259,11 @@ class WirePlugin : Plugin { } private fun Source.outputDir(project: Project): File { - return if (sources.size > 1) File(project.targetDefaultOutputPath(), name) - else File(project.targetDefaultOutputPath()) + return if (sources.size > 1) { + File(project.targetDefaultOutputPath(), name) + } else { + File(project.targetDefaultOutputPath()) + } } private fun Project.addWireRuntimeDependency( @@ -282,7 +285,7 @@ class WirePlugin : Plugin { project.extensions.getByType(KotlinMultiplatformExtension::class.java).sourceSets val sourceSet = (sourceSets.getByName("commonMain") as DefaultKotlinSourceSet) project.configurations.getByName(sourceSet.apiConfigurationName).dependencies.add( - runtimeDependency + runtimeDependency, ) } @@ -291,7 +294,7 @@ class WirePlugin : Plugin { project.extensions.getByType(KotlinJsProjectExtension::class.java).sourceSets val sourceSet = (sourceSets.getByName("main") as DefaultKotlinSourceSet) project.configurations.getByName(sourceSet.apiConfigurationName).dependencies.add( - runtimeDependency + runtimeDependency, ) } @@ -334,7 +337,7 @@ class WirePlugin : Plugin { // 1.7.x: `fun source(vararg sources: Any)` private val SOURCE_FUNCTION = KotlinCompile::class.java.getMethod( "source", - JavaArray.newInstance(Any::class.java, 0).javaClass + JavaArray.newInstance(Any::class.java, 0).javaClass, ) } } diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt index 9c0dcd22ed..2923cde25e 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -22,6 +22,8 @@ import com.squareup.wire.schema.EventListener import com.squareup.wire.schema.Location import com.squareup.wire.schema.Target import com.squareup.wire.schema.WireRun +import java.io.File +import javax.inject.Inject import okio.FileSystem import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty @@ -40,8 +42,6 @@ import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.SourceTask import org.gradle.api.tasks.TaskAction -import java.io.File -import javax.inject.Inject @CacheableTask abstract class WireTask @Inject constructor(objects: ObjectFactory) : SourceTask() { diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/GradleWireLogger.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/GradleWireLogger.kt index f384f090d3..0b56a681b8 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/GradleWireLogger.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/GradleWireLogger.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -28,7 +28,7 @@ internal object GradleWireLogger : WireLogger { slf4jLogger.warn( """Unused element in treeShakingRoots: | ${unusedRoots.joinToString(separator = "\n ")} - """.trimMargin() + """.trimMargin(), ) } @@ -36,7 +36,7 @@ internal object GradleWireLogger : WireLogger { slf4jLogger.warn( """Unused element in treeShakingRubbish: | ${unusedPrunes.joinToString(separator = "\n ")} - """.trimMargin() + """.trimMargin(), ) } @@ -44,7 +44,7 @@ internal object GradleWireLogger : WireLogger { slf4jLogger.warn( """Unused includes in targets: | ${unusedIncludes.joinToString(separator = "\n ")} - """.trimMargin() + """.trimMargin(), ) } @@ -52,7 +52,7 @@ internal object GradleWireLogger : WireLogger { slf4jLogger.warn( """Unused excludes in targets: | ${unusedExcludes.joinToString(separator = "\n ")} - """.trimMargin() + """.trimMargin(), ) } diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt index ed725bc111..ad6fbbada1 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.gradle.internal import org.gradle.api.Project diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt index 3e934a2b98..c84184462d 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -65,7 +65,7 @@ internal fun WirePlugin.sourceRoots(kotlin: Boolean, java: Boolean): List throw IllegalStateException("Unknown Android plugin $this") } val androidSourceSets: Map? = - if (kotlin) null else { + if (kotlin) { + null + } else { sourceSets .associate { sourceSet -> sourceSet.name to sourceSet.java @@ -125,7 +127,9 @@ private fun BaseExtension.sourceRoots(project: Project, kotlin: Boolean): List sourceSet.name to kotlinSourceSets.getByName(sourceSet.name).kotlin } - } else null + } else { + null + } } return variants.map { variant -> @@ -158,8 +162,11 @@ private fun BaseExtension.sourceRoots(project: Project, kotlin: Boolean): List, val registerGeneratedDirectory: ((Provider) -> Unit)? = null, - val registerTaskDependency: ((TaskProvider) -> Unit)? = null + val registerTaskDependency: ((TaskProvider) -> Unit)? = null, ) internal class WireSourceDirectorySet private constructor( @@ -184,7 +191,7 @@ internal class WireSourceDirectorySet private constructor( init { check( (sourceDirectorySet == null || androidSourceDirectorySet == null) && - (sourceDirectorySet != null || androidSourceDirectorySet != null) + (sourceDirectorySet != null || androidSourceDirectorySet != null), ) { "At least and at most one of sourceDirectorySet, androidSourceDirectorySet should be non-null" } diff --git a/wire-gradle-plugin/src/test/kotlin/com/squareup/wire/gradle/WirePluginTest.kt b/wire-gradle-plugin/src/test/kotlin/com/squareup/wire/gradle/WirePluginTest.kt index e2c371b408..ba5fcd47eb 100644 --- a/wire-gradle-plugin/src/test/kotlin/com/squareup/wire/gradle/WirePluginTest.kt +++ b/wire-gradle-plugin/src/test/kotlin/com/squareup/wire/gradle/WirePluginTest.kt @@ -1,9 +1,29 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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. + */ @file:Suppress("UsePropertyAccessSyntax") package com.squareup.wire.gradle import com.squareup.wire.VERSION import com.squareup.wire.testing.withPlatformSlashes +import java.io.File +import java.io.IOException +import java.util.zip.ZipFile +import kotlin.text.RegexOption.DOT_MATCHES_ALL +import kotlin.text.RegexOption.MULTILINE import org.assertj.core.api.Assertions.assertThat import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner @@ -14,11 +34,6 @@ import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder -import java.io.File -import java.io.IOException -import java.util.zip.ZipFile -import kotlin.text.RegexOption.DOT_MATCHES_ALL -import kotlin.text.RegexOption.MULTILINE class WirePluginTest { @@ -83,7 +98,7 @@ class WirePluginTest { | include 'relativePath' | } |} - """.trimMargin() + """.trimMargin(), ) } @@ -180,7 +195,7 @@ class WirePluginTest { | include 'relativePath' | } |} - """.trimMargin() + """.trimMargin(), ) } @@ -193,7 +208,7 @@ class WirePluginTest { assertThat(result.task(":generateProtos")).isNull() assertThat(result.output) .contains( - """Invalid path string: "http://www.squareup.com". URL dependencies are not allowed.""" + """Invalid path string: "http://www.squareup.com". URL dependencies are not allowed.""", ) } @@ -287,7 +302,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcetree-one-srcdir-many-files/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcetree-one-srcdir-many-files/build/generated/source/wire".withPlatformSlashes(), ) } @@ -306,7 +321,7 @@ class WirePluginTest { | squareup.dinosaurs.Crustacean |Unused element(s) in prunes: | squareup.mammals.Human - """.trimMargin() + """.trimMargin(), ) } @@ -334,7 +349,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-local-many-files/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-local-many-files/build/generated/source/wire".withPlatformSlashes(), ) } @@ -349,7 +364,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-local-nonproto-file/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-local-nonproto-file/build/generated/source/wire".withPlatformSlashes(), ) } @@ -364,7 +379,7 @@ class WirePluginTest { .doesNotContain("Writing com.squareup.dinosaurs.Dinosaur") .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-local-single-file/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-local-single-file/build/generated/source/wire".withPlatformSlashes(), ) } @@ -380,7 +395,7 @@ class WirePluginTest { .contains("Writing com.squareup.geology.Period") .doesNotContain("Writing com.excluded.Martian") .contains( - "src/test/projects/sourcejar-mixed-conflicts/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-mixed-conflicts/build/generated/source/wire".withPlatformSlashes(), ) } @@ -395,7 +410,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-remote-many-files/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-remote-many-files/build/generated/source/wire".withPlatformSlashes(), ) } @@ -411,7 +426,7 @@ class WirePluginTest { .contains("Writing com.squareup.geology.Period") .doesNotContain("Writing com.excluded.Martian") .contains( - "src/test/projects/sourcejar-remote-wildcards/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-remote-wildcards/build/generated/source/wire".withPlatformSlashes(), ) } @@ -426,7 +441,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .doesNotContain("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-remote-protopath/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-remote-protopath/build/generated/source/wire".withPlatformSlashes(), ) } @@ -440,7 +455,7 @@ class WirePluginTest { assertThat(result.output) .contains("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcejar-remote-version-catalog/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcejar-remote-version-catalog/build/generated/source/wire".withPlatformSlashes(), ) } @@ -455,7 +470,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .doesNotContain("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcezip-local-protopath/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcezip-local-protopath/build/generated/source/wire".withPlatformSlashes(), ) } @@ -470,7 +485,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .doesNotContain("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourceaar-local-protopath/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourceaar-local-protopath/build/generated/source/wire".withPlatformSlashes(), ) } @@ -486,15 +501,15 @@ class WirePluginTest { .isIn(TaskOutcome.SUCCESS, TaskOutcome.UP_TO_DATE) val generatedProto1 = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/dinosaurs/Dinosaur.kt" + "dinosaurs/build/generated/source/wire/com/squareup/dinosaurs/Dinosaur.kt", ) val generatedProto2 = File( fixtureRoot, - "geology/build/generated/source/wire/com/squareup/geology/Period.kt" + "geology/build/generated/source/wire/com/squareup/geology/Period.kt", ) val generatedProto3 = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/location/Continent.kt" + "dinosaurs/build/generated/source/wire/com/squareup/location/Continent.kt", ) assertThat(generatedProto1).exists() assertThat(generatedProto2).exists() @@ -502,7 +517,7 @@ class WirePluginTest { val notExpected = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/location/Planet.kt" + "dinosaurs/build/generated/source/wire/com/squareup/location/Planet.kt", ) assertThat(notExpected).doesNotExist() @@ -570,7 +585,7 @@ class WirePluginTest { assertThat(result.task(":generateProtos")).isNull() assertThat(result.output) .contains( - "Wire Gradle plugin applied in project ':' but no supported Kotlin plugin was found" + "Wire Gradle plugin applied in project ':' but no supported Kotlin plugin was found", ) } @@ -834,7 +849,7 @@ class WirePluginTest { .contains("Writing com.squareup.dinosaurs.Dinosaur") .doesNotContain("Writing com.squareup.geology.Period") .contains( - "src/test/projects/sourcepath-and-protopath-intersect/build/generated/source/wire".withPlatformSlashes() + "src/test/projects/sourcepath-and-protopath-intersect/build/generated/source/wire".withPlatformSlashes(), ) } @@ -954,10 +969,10 @@ class WirePluginTest { val outputRoot = File(fixtureRoot, "build/generated/source/wire") assertThat(File(outputRoot, "com/squareup/dinosaurs/BattleServiceClient.kt")).exists() assertThat( - File(outputRoot, "com/squareup/dinosaurs/BattleServiceFightBlockingServer.kt") + File(outputRoot, "com/squareup/dinosaurs/BattleServiceFightBlockingServer.kt"), ).exists() assertThat( - File(outputRoot, "com/squareup/dinosaurs/BattleServiceBrawlBlockingServer.kt") + File(outputRoot, "com/squareup/dinosaurs/BattleServiceBrawlBlockingServer.kt"), ).exists() } @@ -1022,7 +1037,7 @@ class WirePluginTest { "custom handler is running!! " + "squareup.dinosaurs.Dinosaur, " + "squareup.geology.Period, true, " + - "a=one, b=two, c=three" + "a=one, b=two, c=three", ) } @@ -1081,7 +1096,11 @@ class WirePluginTest { val result = gradleRunner.runFixture(fixtureRoot) { withArguments( - "assemble", "--stacktrace", "-Dkjs=$kmpJsEnabled", "-Dknative=$kmpNativeEnabled", "--info" + "assemble", + "--stacktrace", + "-Dkjs=$kmpJsEnabled", + "-Dknative=$kmpNativeEnabled", + "--info", ).build() } @@ -1205,7 +1224,8 @@ class WirePluginTest { assertThat(result.output).contains("Writing squareup.options.DocumentationUrlOption") val generatedProto = File( - fixtureRoot, "build/generated/source/wire/squareup/polygons/Octagon.java" + fixtureRoot, + "build/generated/source/wire/squareup/polygons/Octagon.java", ) val octagon = generatedProto.readText() assertThat(octagon) @@ -1222,7 +1242,8 @@ class WirePluginTest { assertThat(result.output).contains("Writing squareup.options.DocumentationUrlOption") val generatedProto = File( - fixtureRoot, "build/generated/source/wire/squareup/polygons/Octagon.kt" + fixtureRoot, + "build/generated/source/wire/squareup/polygons/Octagon.kt", ) val octagon = generatedProto.readText() assertThat(octagon) @@ -1261,15 +1282,15 @@ class WirePluginTest { .isIn(TaskOutcome.SUCCESS, TaskOutcome.UP_TO_DATE) val generatedProto1 = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/dinosaurs/Dinosaur.kt" + "dinosaurs/build/generated/source/wire/com/squareup/dinosaurs/Dinosaur.kt", ) val generatedProto2 = File( fixtureRoot, - "geology/build/generated/source/wire/com/squareup/geology/Period.kt" + "geology/build/generated/source/wire/com/squareup/geology/Period.kt", ) val generatedProto3 = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/location/Continent.kt" + "dinosaurs/build/generated/source/wire/com/squareup/location/Continent.kt", ) assertThat(generatedProto1).exists() assertThat(generatedProto2).exists() @@ -1277,7 +1298,7 @@ class WirePluginTest { val notExpected = File( fixtureRoot, - "dinosaurs/build/generated/source/wire/com/squareup/location/Planet.kt" + "dinosaurs/build/generated/source/wire/com/squareup/location/Planet.kt", ) assertThat(notExpected).doesNotExist() @@ -1408,7 +1429,7 @@ class WirePluginTest { private fun GradleRunner.runFixture( root: File, - action: GradleRunner.() -> BuildResult + action: GradleRunner.() -> BuildResult, ): BuildResult { var generatedSettings = false val settings = File(root, "settings.gradle") @@ -1459,7 +1480,8 @@ class WirePluginTest { } // This follows symlink so don't use it at home. - @Throws(IOException::class) fun unsafeDelete(f: File) { + @Throws(IOException::class) + fun unsafeDelete(f: File) { if (f.isDirectory) { for (c in f.listFiles()!!) unsafeDelete(c) } diff --git a/wire-gradle-plugin/src/test/projects/java-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.java b/wire-gradle-plugin/src/test/projects/java-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.java index f4260af01b..6f8a3a0c02 100644 --- a/wire-gradle-plugin/src/test/projects/java-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.java +++ b/wire-gradle-plugin/src/test/projects/java-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs; import com.squareup.geology.Period; @@ -8,13 +23,14 @@ public final class Sample { public void run() throws IOException { // Create an immutable value object with the Builder API. - Dinosaur stegosaurus = new Dinosaur.Builder() - .name("Stegosaurus") - .period(Period.JURASSIC) - .length_meters(9.0) - .mass_kilograms(5_000.0) - .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) - .build(); + Dinosaur stegosaurus = + new Dinosaur.Builder() + .name("Stegosaurus") + .period(Period.JURASSIC) + .length_meters(9.0) + .mass_kilograms(5_000.0) + .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) + .build(); // Encode that value to bytes, and print that as base64. byte[] stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus); diff --git a/wire-gradle-plugin/src/test/projects/java-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.java b/wire-gradle-plugin/src/test/projects/java-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.java index f4260af01b..6f8a3a0c02 100644 --- a/wire-gradle-plugin/src/test/projects/java-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.java +++ b/wire-gradle-plugin/src/test/projects/java-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.java @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs; import com.squareup.geology.Period; @@ -8,13 +23,14 @@ public final class Sample { public void run() throws IOException { // Create an immutable value object with the Builder API. - Dinosaur stegosaurus = new Dinosaur.Builder() - .name("Stegosaurus") - .period(Period.JURASSIC) - .length_meters(9.0) - .mass_kilograms(5_000.0) - .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) - .build(); + Dinosaur stegosaurus = + new Dinosaur.Builder() + .name("Stegosaurus") + .period(Period.JURASSIC) + .length_meters(9.0) + .mass_kilograms(5_000.0) + .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) + .build(); // Encode that value to bytes, and print that as base64. byte[] stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus); diff --git a/wire-gradle-plugin/src/test/projects/kotlin-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.kt b/wire-gradle-plugin/src/test/projects/kotlin-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.kt index 7fa5aa419b..e2bfdf2948 100644 --- a/wire-gradle-plugin/src/test/projects/kotlin-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.kt +++ b/wire-gradle-plugin/src/test/projects/kotlin-project-java-protos/src/main/java/com/squareup/dinosaurs/Sample.kt @@ -1,8 +1,23 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs import com.squareup.geology.Period -import okio.ByteString.Companion.toByteString import java.io.IOException +import okio.ByteString.Companion.toByteString class Sample { @Throws(IOException::class) diff --git a/wire-gradle-plugin/src/test/projects/kotlin-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.kt b/wire-gradle-plugin/src/test/projects/kotlin-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.kt index f7a8bfbd41..40d8b49602 100644 --- a/wire-gradle-plugin/src/test/projects/kotlin-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.kt +++ b/wire-gradle-plugin/src/test/projects/kotlin-project-kotlin-protos/src/main/java/com/squareup/dinosaurs/Sample.kt @@ -1,8 +1,23 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs import com.squareup.geology.Period -import okio.ByteString.Companion.toByteString import java.io.IOException +import okio.ByteString.Companion.toByteString class Sample { @Throws(IOException::class) @@ -13,7 +28,7 @@ class Sample { period = Period.JURASSIC, length_meters = 9.0, mass_kilograms = 5_000.0, - picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67") + picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67"), ) // Encode that value to bytes, and print that as base64. val stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus) diff --git a/wire-gradle-plugin/src/test/projects/sourcedir-exclude/src/main/java/com/squareup/dinosaurs/Sample.kt b/wire-gradle-plugin/src/test/projects/sourcedir-exclude/src/main/java/com/squareup/dinosaurs/Sample.kt index f7a8bfbd41..40d8b49602 100644 --- a/wire-gradle-plugin/src/test/projects/sourcedir-exclude/src/main/java/com/squareup/dinosaurs/Sample.kt +++ b/wire-gradle-plugin/src/test/projects/sourcedir-exclude/src/main/java/com/squareup/dinosaurs/Sample.kt @@ -1,8 +1,23 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs import com.squareup.geology.Period -import okio.ByteString.Companion.toByteString import java.io.IOException +import okio.ByteString.Companion.toByteString class Sample { @Throws(IOException::class) @@ -13,7 +28,7 @@ class Sample { period = Period.JURASSIC, length_meters = 9.0, mass_kilograms = 5_000.0, - picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67") + picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67"), ) // Encode that value to bytes, and print that as base64. val stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus) diff --git a/wire-gradle-plugin/src/test/projects/sourcedir-include/src/main/java/com/squareup/dinosaurs/Sample.kt b/wire-gradle-plugin/src/test/projects/sourcedir-include/src/main/java/com/squareup/dinosaurs/Sample.kt index f7a8bfbd41..40d8b49602 100644 --- a/wire-gradle-plugin/src/test/projects/sourcedir-include/src/main/java/com/squareup/dinosaurs/Sample.kt +++ b/wire-gradle-plugin/src/test/projects/sourcedir-include/src/main/java/com/squareup/dinosaurs/Sample.kt @@ -1,8 +1,23 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.dinosaurs import com.squareup.geology.Period -import okio.ByteString.Companion.toByteString import java.io.IOException +import okio.ByteString.Companion.toByteString class Sample { @Throws(IOException::class) @@ -13,7 +28,7 @@ class Sample { period = Period.JURASSIC, length_meters = 9.0, mass_kilograms = 5_000.0, - picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67") + picture_urls = listOf("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67"), ) // Encode that value to bytes, and print that as base64. val stegosaurusEncoded = Dinosaur.ADAPTER.encode(stegosaurus) diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcCall.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcCall.kt index 412c820463..b9fbd17e00 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcCall.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcCall.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcClient.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcClient.kt index 4ee3a61200..deff0315e5 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcClient.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcClient.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcException.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcException.kt index e45a3ddf88..4f37904561 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcException.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcException.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.squareup.wire import okio.IOException diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHeaders.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHeaders.kt index bdd4acbb37..980847f649 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHeaders.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHeaders.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt index 545e40bb18..205f61b584 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcMethod.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcMethod.kt index c5867c0fd2..3543797967 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcMethod.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcMethod.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -18,5 +18,5 @@ package com.squareup.wire class GrpcMethod( val path: String, val requestAdapter: ProtoAdapter, - val responseAdapter: ProtoAdapter + val responseAdapter: ProtoAdapter, ) diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequest.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequest.kt index 3d412b8c65..9f8b1b7521 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequest.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.squareup.wire expect class GrpcRequest diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequestBody.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequestBody.kt index 3cd7ba1aab..419b15660e 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequestBody.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcRequestBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt index 9931ddb307..c021f3bf73 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponse.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -18,12 +18,13 @@ package com.squareup.wire import com.squareup.wire.internal.addSuppressed -import okio.IOException import kotlin.jvm.JvmName import kotlin.jvm.JvmOverloads +import okio.IOException expect class GrpcResponse { - @get:JvmName("body") val body: GrpcResponseBody? + @get:JvmName("body") + val body: GrpcResponseBody? @JvmOverloads fun header(name: String, defaultValue: String? = null): String? diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponseBody.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponseBody.kt index bc2fbbadbc..007d938f6f 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponseBody.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcResponseBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.squareup.wire import okio.BufferedSource diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt index 163e4b41a9..23bd4d4328 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.squareup.wire import kotlin.jvm.JvmField @@ -21,27 +20,43 @@ import kotlin.jvm.Synchronized class GrpcStatus private constructor( val name: String, - val code: Int + val code: Int, ) { companion object { private val INSTANCES = mutableMapOf() @JvmField val OK: GrpcStatus = create("OK", 0) + @JvmField val CANCELLED: GrpcStatus = create("CANCELLED", 1) + @JvmField val UNKNOWN: GrpcStatus = create("UNKNOWN", 2) + @JvmField val INVALID_ARGUMENT: GrpcStatus = create("INVALID_ARGUMENT", 3) + @JvmField val DEADLINE_EXCEEDED: GrpcStatus = create("DEADLINE_EXCEEDED", 4) + @JvmField val NOT_FOUND: GrpcStatus = create("NOT_FOUND", 5) + @JvmField val ALREADY_EXISTS: GrpcStatus = create("ALREADY_EXISTS", 6) + @JvmField val PERMISSION_DENIED: GrpcStatus = create("PERMISSION_DENIED", 7) + @JvmField val RESOURCE_EXHAUSTED: GrpcStatus = create("RESOURCE_EXHAUSTED", 8) + @JvmField val FAILED_PRECONDITION: GrpcStatus = create("FAILED_PRECONDITION", 9) + @JvmField val ABORTED: GrpcStatus = create("ABORTED", 10) + @JvmField val OUT_OF_RANGE: GrpcStatus = create("OUT_OF_RANGE", 11) + @JvmField val UNIMPLEMENTED: GrpcStatus = create("UNIMPLEMENTED", 12) + @JvmField val INTERNAL: GrpcStatus = create("INTERNAL", 13) + @JvmField val UNAVAILABLE: GrpcStatus = create("UNAVAILABLE", 14) + @JvmField val DATA_LOSS: GrpcStatus = create("DATA_LOSS", 15) + @JvmField val UNAUTHENTICATED: GrpcStatus = create("UNAUTHENTICATED", 16) private fun create(name: String, status: Int): GrpcStatus { diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStreamingCall.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStreamingCall.kt index 9ab8b3e69d..2b4261c9ee 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStreamingCall.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStreamingCall.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -96,8 +96,8 @@ interface GrpcStreamingCall { message = "Provide a scope, preferably not GlobalScope", replaceWith = ReplaceWith( expression = "executeIn(GlobalScope)", - imports = ["kotlinx.coroutines.GlobalScope"] - ) + imports = ["kotlinx.coroutines.GlobalScope"], + ), ) fun execute(): Pair, ReceiveChannel> diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/WireGrpcExperimental.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/WireGrpcExperimental.kt index 7491fc9cdd..039057d3e4 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/WireGrpcExperimental.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/WireGrpcExperimental.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.squareup.wire import kotlinx.coroutines.ExperimentalCoroutinesApi diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt index c891ee6524..ef311cf573 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt index 3b0ed86c85..5a998211f7 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSink.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSink.kt index bb76321998..27acdc7d44 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSink.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSink.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -33,7 +33,7 @@ class GrpcMessageSink( private val minMessageToCompress: Long, private val messageAdapter: ProtoAdapter, private val callForCancel: Call?, - private val grpcEncoding: String + private val grpcEncoding: String, ) : MessageSink { private var closed = false override fun write(message: T) { diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSource.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSource.kt index 896bd321c9..3f957473f6 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSource.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcMessageSource.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -31,7 +31,7 @@ import okio.buffer class GrpcMessageSource( private val source: BufferedSource, private val messageAdapter: ProtoAdapter, - private val grpcEncoding: String? = null + private val grpcEncoding: String? = null, ) : MessageSource { override fun read(): T? { if (source.exhausted()) return null @@ -46,7 +46,7 @@ class GrpcMessageSource( compressedFlag.toInt() == 0 -> GrpcDecoder.IdentityGrpcDecoder compressedFlag.toInt() == 1 -> { grpcEncoding?.toGrpcDecoding() ?: throw ProtocolException( - "message is encoded but message-encoding header was omitted" + "message is encoded but message-encoding header was omitted", ) } else -> throw ProtocolException("unexpected compressed-flag: $compressedFlag") diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/platform.common.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/platform.common.kt index fe0402f968..8f1d430066 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/platform.common.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/platform.common.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/util.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/util.kt index 6f2e14a327..697dd319c3 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/util.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/util.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcClient.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcClient.kt index 77d0cd3048..cfd6b41d9f 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcClient.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcClient.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHeaders.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHeaders.kt index 36f75d003e..b31a389465 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHeaders.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHeaders.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt index 2bb9b89de7..69714cbf4d 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequest.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequest.kt index f69dc65c31..fba5417072 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequest.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -21,11 +21,11 @@ actual open class GrpcRequestBuilder { actual open fun url(url: GrpcHttpUrl): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun addHeader( name: String, - value: String + value: String, ): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun method( method: String, - body: GrpcRequestBody? + body: GrpcRequestBody?, ): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun build(): GrpcRequest = TODO("Not yet implemented") } diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequestBody.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequestBody.kt index 8892a872c9..64a54e1288 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequestBody.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcRequestBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponse.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponse.kt index 409fbaa0ce..f57c38a409 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponse.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponse.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -21,7 +21,7 @@ actual class GrpcResponse { actual fun header( name: String, - defaultValue: String? + defaultValue: String?, ): String? { TODO("Not yet implemented") } diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponseBody.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponseBody.kt index 8f610a9ed4..f46dc85c8b 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponseBody.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/GrpcResponseBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt index 542a815f0e..61fc943fae 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt index b502d94435..a6dd1ba971 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -17,6 +17,7 @@ package com.squareup.wire +import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope @@ -28,7 +29,6 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import okio.IOException import okio.Timeout -import java.util.concurrent.atomic.AtomicBoolean /** * Returns a new instance of [GrpcCall] that can be used for a single call to @@ -70,7 +70,7 @@ fun GrpcCall(function: (S) -> R): GrpcCall { get() = GrpcMethod( path = "/wire/AnonymousEndpoint", requestAdapter = ProtoAdapter.BYTES, - responseAdapter = ProtoAdapter.BYTES + responseAdapter = ProtoAdapter.BYTES, ) as GrpcMethod override val timeout: Timeout = Timeout.NONE @@ -145,7 +145,7 @@ fun GrpcCall(function: (S) -> R): GrpcCall { */ @JvmName("grpcStreamingCall") fun GrpcStreamingCall( - function: suspend (ReceiveChannel, SendChannel) -> Unit + function: suspend (ReceiveChannel, SendChannel) -> Unit, ): GrpcStreamingCall { return object : GrpcStreamingCall { @Suppress("UNCHECKED_CAST") @@ -153,7 +153,7 @@ fun GrpcStreamingCall( get() = GrpcMethod( path = "/wire/AnonymousEndpoint", requestAdapter = ProtoAdapter.BYTES, - responseAdapter = ProtoAdapter.BYTES + responseAdapter = ProtoAdapter.BYTES, ) as GrpcMethod private var canceled = AtomicBoolean() diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt index 20e22d381d..98846cbda6 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -17,16 +17,16 @@ package com.squareup.wire import com.squareup.wire.internal.RealGrpcCall import com.squareup.wire.internal.RealGrpcStreamingCall +import kotlin.reflect.KClass import okhttp3.Call import okhttp3.OkHttpClient import okhttp3.Protocol.H2_PRIOR_KNOWLEDGE import okhttp3.Protocol.HTTP_2 -import kotlin.reflect.KClass actual abstract class GrpcClient private constructor( internal val client: Call.Factory, internal val baseUrl: GrpcHttpUrl, - internal val minMessageToCompress: Long + internal val minMessageToCompress: Long, ) { /** Returns a [T] that makes gRPC calls using this client. */ inline fun create(): T = create(T::class) @@ -68,7 +68,7 @@ actual abstract class GrpcClient private constructor( internal fun newCall( method: GrpcMethod<*, *>, requestMetadata: Map, - requestBody: GrpcRequestBody + requestBody: GrpcRequestBody, ): Call { return client.newCall( GrpcRequestBuilder() @@ -86,7 +86,7 @@ actual abstract class GrpcClient private constructor( } .tag(GrpcMethod::class.java, method) .method("POST", requestBody) - .build() + .build(), ) } @@ -132,7 +132,7 @@ actual abstract class GrpcClient private constructor( fun build(): GrpcClient = object : GrpcClient( client = client ?: throw IllegalArgumentException("client is not set"), baseUrl = baseUrl ?: throw IllegalArgumentException("baseUrl is not set"), - minMessageToCompress = minMessageToCompress + minMessageToCompress = minMessageToCompress, ) { override fun newCall(method: GrpcMethod): GrpcCall { return RealGrpcCall(this, method) diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHeaders.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHeaders.kt index 1d95352adb..7dd11e9f1c 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHeaders.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHeaders.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt index c3cfa2d740..c7ad47510a 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequest.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequest.kt index a3600752bf..22bc78ccac 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequest.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequestBody.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequestBody.kt index f3e3826ce9..796c1193c8 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequestBody.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcRequestBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt index e99cd042b1..c71ed98bd3 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponseBody.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponseBody.kt index 041b290648..e577c69ad7 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponseBody.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponseBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt index ea64da0747..4483ff44eb 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -19,10 +19,10 @@ import com.squareup.wire.GrpcResponse import com.squareup.wire.MessageSource import com.squareup.wire.ProtoAdapter import com.squareup.wire.use +import java.util.concurrent.LinkedBlockingDeque import okhttp3.Call import okhttp3.Callback import okio.IOException -import java.util.concurrent.LinkedBlockingDeque /** * This message source uses a [LinkedBlockingDeque] to connect a reading source with a writing @@ -36,7 +36,7 @@ import java.util.concurrent.LinkedBlockingDeque internal class BlockingMessageSource( val grpcCall: RealGrpcStreamingCall<*, R>, val responseAdapter: ProtoAdapter, - val call: Call + val call: Call, ) : MessageSource { private val queue = LinkedBlockingDeque(1) diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/LateInitTimeout.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/LateInitTimeout.kt index 7de694ed73..cb9417058e 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/LateInitTimeout.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/LateInitTimeout.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -15,9 +15,9 @@ */ package com.squareup.wire.internal +import java.util.concurrent.TimeUnit import okio.ForwardingTimeout import okio.Timeout -import java.util.concurrent.TimeUnit internal class LateInitTimeout : ForwardingTimeout(Timeout()) { fun init(newDelegate: Timeout) { diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/PipeDuplexRequestBody.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/PipeDuplexRequestBody.kt index 88850276c6..7cac4ec079 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/PipeDuplexRequestBody.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/PipeDuplexRequestBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -26,7 +26,7 @@ import okio.buffer */ internal class PipeDuplexRequestBody( private val contentType: MediaType?, - pipeMaxBufferSize: Long + pipeMaxBufferSize: Long, ) : RequestBody() { private val pipe = Pipe(pipeMaxBufferSize) diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcCall.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcCall.kt index 92638b5fac..d4b3223a73 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcCall.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcCall.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -20,18 +20,18 @@ import com.squareup.wire.GrpcClient import com.squareup.wire.GrpcMethod import com.squareup.wire.GrpcResponse import com.squareup.wire.use +import java.util.concurrent.TimeUnit +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.Callback import okhttp3.Response import okio.IOException import okio.Timeout -import java.util.concurrent.TimeUnit -import kotlin.coroutines.resume -import kotlin.coroutines.resumeWithException internal class RealGrpcCall( private val grpcClient: GrpcClient, - override val method: GrpcMethod + override val method: GrpcMethod, ) : GrpcCall { /** Non-null once this is executed. */ private var call: Call? = null @@ -137,7 +137,7 @@ internal class RealGrpcCall( val requestBody = newRequestBody( minMessageToCompress = grpcClient.minMessageToCompress, requestAdapter = method.requestAdapter, - onlyMessage = request + onlyMessage = request, ) val result = grpcClient.newCall(method, requestMetadata, requestBody) this.call = result diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcStreamingCall.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcStreamingCall.kt index c4f1709c58..9e40579b66 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcStreamingCall.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcStreamingCall.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -20,6 +20,8 @@ import com.squareup.wire.GrpcMethod import com.squareup.wire.GrpcStreamingCall import com.squareup.wire.MessageSink import com.squareup.wire.MessageSource +import java.util.concurrent.TimeUnit +import kotlin.DeprecationLevel.WARNING import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -29,14 +31,13 @@ import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.launch import okio.Timeout -import java.util.concurrent.TimeUnit -import kotlin.DeprecationLevel.WARNING internal class RealGrpcStreamingCall( private val grpcClient: GrpcClient, - override val method: GrpcMethod + override val method: GrpcMethod, ) : GrpcStreamingCall { private val requestBody = newDuplexRequestBody() + /** Non-null once this is executed. */ private var call: Call? = null private var canceled = false @@ -63,7 +64,7 @@ internal class RealGrpcStreamingCall( @Deprecated( "Provide a scope, preferably not GlobalScope", replaceWith = ReplaceWith("executeIn(GlobalScope)", "kotlinx.coroutines.GlobalScope"), - level = WARNING + level = WARNING, ) @Suppress("OPT_IN_USAGE") override fun execute(): Pair, ReceiveChannel> = executeIn(GlobalScope) @@ -87,7 +88,7 @@ internal class RealGrpcStreamingCall( requestBody = requestBody, minMessageToCompress = grpcClient.minMessageToCompress, requestAdapter = method.requestAdapter, - callForCancel = call + callForCancel = call, ) } call.enqueue(responseChannel.readFromResponseBodyCallback(this, method.responseAdapter)) @@ -101,7 +102,7 @@ internal class RealGrpcStreamingCall( val messageSink = requestBody.messageSink( minMessageToCompress = grpcClient.minMessageToCompress, requestAdapter = method.requestAdapter, - callForCancel = call + callForCancel = call, ) call.enqueue(messageSource.readFromResponseBodyCallback()) @@ -115,8 +116,11 @@ internal class RealGrpcStreamingCall( val oldTimeout = this.timeout result.timeout.also { newTimeout -> newTimeout.timeout(oldTimeout.timeoutNanos(), TimeUnit.NANOSECONDS) - if (oldTimeout.hasDeadline()) newTimeout.deadlineNanoTime(oldTimeout.deadlineNanoTime()) - else newTimeout.clearDeadline() + if (oldTimeout.hasDeadline()) { + newTimeout.deadlineNanoTime(oldTimeout.deadlineNanoTime()) + } else { + newTimeout.clearDeadline() + } } result.requestMetadata += this.requestMetadata return result diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt index 26dc83d9b0..81c3562ebc 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -20,6 +20,8 @@ import com.squareup.wire.GrpcResponse import com.squareup.wire.GrpcStatus import com.squareup.wire.ProtoAdapter import com.squareup.wire.use +import java.io.Closeable +import java.util.Base64 import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel @@ -33,8 +35,6 @@ import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody import okio.BufferedSink import okio.IOException -import java.io.Closeable -import java.util.Base64 internal val APPLICATION_GRPC_MEDIA_TYPE: MediaType = "application/grpc".toMediaType() @@ -42,7 +42,7 @@ internal val APPLICATION_GRPC_MEDIA_TYPE: MediaType = "application/grpc".toMedia internal fun newRequestBody( minMessageToCompress: Long, requestAdapter: ProtoAdapter, - onlyMessage: S + onlyMessage: S, ): RequestBody { return object : RequestBody() { override fun contentType() = APPLICATION_GRPC_MEDIA_TYPE @@ -74,7 +74,7 @@ internal fun newDuplexRequestBody(): PipeDuplexRequestBody { internal fun PipeDuplexRequestBody.messageSink( minMessageToCompress: Long, requestAdapter: ProtoAdapter, - callForCancel: Call + callForCancel: Call, ) = GrpcMessageSink( sink = createSink(), minMessageToCompress = minMessageToCompress, @@ -86,7 +86,7 @@ internal fun PipeDuplexRequestBody.messageSink( /** Sends the response messages to the channel. */ internal fun SendChannel.readFromResponseBodyCallback( grpcCall: RealGrpcStreamingCall<*, R>, - responseAdapter: ProtoAdapter + responseAdapter: ProtoAdapter, ): Callback { return object : Callback { override fun onFailure(call: Call, e: IOException) { @@ -141,7 +141,7 @@ internal suspend fun ReceiveChannel.writeToRequestBody( requestBody: PipeDuplexRequestBody, minMessageToCompress: Long, requestAdapter: ProtoAdapter, - callForCancel: Call + callForCancel: Call, ) { val requestWriter = requestBody.messageSink(minMessageToCompress, requestAdapter, callForCancel) try { @@ -168,7 +168,7 @@ internal suspend fun ReceiveChannel.writeToRequestBody( /** Reads messages from the response body. */ internal fun GrpcResponse.messageSource( - protoAdapter: ProtoAdapter + protoAdapter: ProtoAdapter, ): GrpcMessageSource { checkGrpcResponse() val grpcEncoding = header("grpc-encoding") @@ -210,7 +210,7 @@ internal fun GrpcResponse.grpcResponseToException(suppressed: IOException? = nul throw IOException( "gRPC transport failure, invalid grpc-status-details-bin" + " (HTTP status=$code, grpc-status=$grpcStatus, grpc-message=$grpcMessage)", - e + e, ) } } @@ -222,7 +222,7 @@ internal fun GrpcResponse.grpcResponseToException(suppressed: IOException? = nul return IOException( "gRPC transport failure" + " (HTTP status=$code, grpc-status=$grpcStatus, grpc-message=$grpcMessage)", - transportException + transportException, ) } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt index 7e78429a64..00f4efe20b 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -15,15 +15,16 @@ */ package com.squareup.wire.internal +import java.lang.reflect.Method import okio.Sink import okio.Source import okio.gzip -import java.lang.reflect.Method actual typealias Call = okhttp3.Call @Suppress("NOTHING_TO_INLINE") internal actual inline fun Sink.asGzip(): Sink = gzip() + @Suppress("NOTHING_TO_INLINE") internal actual inline fun Source.asGzip(): Source = gzip() diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcClient.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcClient.kt index 77d0cd3048..cfd6b41d9f 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcClient.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcClient.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHeaders.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHeaders.kt index 36f75d003e..b31a389465 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHeaders.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHeaders.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt index 2bb9b89de7..69714cbf4d 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcHttpUrl.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequest.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequest.kt index f69dc65c31..fba5417072 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequest.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -21,11 +21,11 @@ actual open class GrpcRequestBuilder { actual open fun url(url: GrpcHttpUrl): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun addHeader( name: String, - value: String + value: String, ): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun method( method: String, - body: GrpcRequestBody? + body: GrpcRequestBody?, ): GrpcRequestBuilder = TODO("Not yet implemented") actual open fun build(): GrpcRequest = TODO("Not yet implemented") } diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequestBody.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequestBody.kt index 8892a872c9..64a54e1288 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequestBody.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcRequestBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponse.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponse.kt index 409fbaa0ce..f57c38a409 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponse.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponse.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -21,7 +21,7 @@ actual class GrpcResponse { actual fun header( name: String, - defaultValue: String? + defaultValue: String?, ): String? { TODO("Not yet implemented") } diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponseBody.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponseBody.kt index 8f610a9ed4..f46dc85c8b 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponseBody.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/GrpcResponseBody.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt index e833c4009a..adf216d088 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-mockwebserver/src/main/java/com/squareup/wire/mockwebserver/GrpcDispatcher.kt b/wire-grpc-mockwebserver/src/main/java/com/squareup/wire/mockwebserver/GrpcDispatcher.kt index 0adb7b69cc..2f5ce2ae76 100644 --- a/wire-grpc-mockwebserver/src/main/java/com/squareup/wire/mockwebserver/GrpcDispatcher.kt +++ b/wire-grpc-mockwebserver/src/main/java/com/squareup/wire/mockwebserver/GrpcDispatcher.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -22,6 +22,7 @@ import com.squareup.wire.ProtoAdapter import com.squareup.wire.Service import com.squareup.wire.internal.GrpcMessageSink import com.squareup.wire.internal.GrpcMessageSource +import java.lang.reflect.Method import okhttp3.Call import okhttp3.Callback import okhttp3.Headers.Companion.headersOf @@ -31,7 +32,6 @@ import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.RecordedRequest import okio.Buffer import okio.Timeout -import java.lang.reflect.Method /** * Serves gRPC calls using MockWebServer over HTTP/2. @@ -129,7 +129,7 @@ class GrpcDispatcher( private fun dispatchGrpc( endpoint: Endpoint, - recordedRequest: RecordedRequest + recordedRequest: RecordedRequest, ): MockResponse { // TODO(oldergod): recover gracefully if the parameters don't decode to the expected types. @@ -152,19 +152,19 @@ class GrpcDispatcher( private fun decodeRequest( request: RecordedRequest, - protoAdapter: ProtoAdapter + protoAdapter: ProtoAdapter, ): S { val source = GrpcMessageSource( source = request.body, messageAdapter = protoAdapter, - grpcEncoding = request.headers["grpc-encoding"] + grpcEncoding = request.headers["grpc-encoding"], ) return source.readExactlyOneAndClose() } private fun encodeResponse( response: R, - protoAdapter: ProtoAdapter + protoAdapter: ProtoAdapter, ): Buffer { val result = Buffer() GrpcMessageSink( @@ -182,7 +182,7 @@ class GrpcDispatcher( private class Endpoint( val grpcMethod: GrpcMethod, val javaMethod: Method, - val service: Service + val service: Service, ) { @Suppress("UNCHECKED_CAST") // The GrpcCall type and GrpcMethod type always align. fun newGrpcCall(): GrpcCall = javaMethod.invoke(service) as GrpcCall diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterGenerator.kt index ecc123a275..294325b721 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,12 +15,17 @@ */ package com.squareup.wire.kotlin.grpcserver -import com.squareup.kotlinpoet.* +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.CodeBlock +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.KModifier +import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy +import com.squareup.kotlinpoet.PropertySpec +import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.kotlin.grpcserver.ImplBaseGenerator.addImplBaseRpcSignature import com.squareup.wire.schema.Service import java.util.concurrent.ExecutorService -import kotlinx.coroutines.channels.Channel object BindableAdapterGenerator { @@ -28,13 +33,13 @@ object BindableAdapterGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { val serviceClassName = generator.classNameFor(service.type) val implBaseClassName = ClassName( serviceClassName.packageName, "${service.name}WireGrpc", - "${service.name}ImplBase" + "${service.name}ImplBase", ) return builder .addType( @@ -42,31 +47,34 @@ object BindableAdapterGenerator { .superclass(implBaseClassName) .primaryConstructor( FunSpec.constructorBuilder() - .apply { if (!options.suspendingCalls) { - // non suspending calls need an executor for the streaming calls - // suspending calls use CoroutineContext instead - this.addParameter( - name = "streamExecutor", - type = ExecutorService::class - ) - } } - + .apply { + if (!options.suspendingCalls) { + // non suspending calls need an executor for the streaming calls + // suspending calls use CoroutineContext instead + this.addParameter( + name = "streamExecutor", + type = ExecutorService::class, + ) + } + } .apply { addRpcConstructorParameters(generator, this, service, options) } - .build() + .build(), ) - .apply { if (!options.suspendingCalls) { - this.addProperty( - PropertySpec.builder("streamExecutor", ExecutorService::class) - .addModifiers(KModifier.PRIVATE) - .initializer("streamExecutor") - .build() - ) - } } + .apply { + if (!options.suspendingCalls) { + this.addProperty( + PropertySpec.builder("streamExecutor", ExecutorService::class) + .addModifiers(KModifier.PRIVATE) + .initializer("streamExecutor") + .build(), + ) + } + } .apply { addRpcProperties(generator, this, service, options) addRpcAdapterCodeBlocks(generator, this, service, options) } - .build() + .build(), ) } @@ -74,7 +82,7 @@ object BindableAdapterGenerator { generator: ClassNameGenerator, builder: FunSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): FunSpec.Builder { val serviceSuffix = if (options.suspendingCalls) { SUSPENDING_SERVER_SUFFIX @@ -88,9 +96,9 @@ object BindableAdapterGenerator { type = LambdaTypeName.get( returnType = ClassName( generator.classNameFor(service.type).packageName, - "${service.name}${rpc.name}${serviceSuffix}" - ) - ) + "${service.name}${rpc.name}$serviceSuffix", + ), + ), ) } } else { @@ -99,9 +107,9 @@ object BindableAdapterGenerator { type = LambdaTypeName.get( returnType = ClassName( generator.classNameFor(service.type).packageName, - "${service.name}${serviceSuffix}" - ) - ) + "${service.name}$serviceSuffix", + ), + ), ) } return builder @@ -111,7 +119,7 @@ object BindableAdapterGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { val serviceSuffix = if (options.suspendingCalls) { SUSPENDING_SERVER_SUFFIX @@ -126,13 +134,13 @@ object BindableAdapterGenerator { type = LambdaTypeName.get( returnType = ClassName( generator.classNameFor(service.type).packageName, - "${service.name}${rpc.name}${serviceSuffix}" - ) - ) + "${service.name}${rpc.name}$serviceSuffix", + ), + ), ) .initializer(rpc.name) .addModifiers(KModifier.PRIVATE) - .build() + .build(), ) } } else { @@ -142,13 +150,13 @@ object BindableAdapterGenerator { type = LambdaTypeName.get( returnType = ClassName( generator.classNameFor(service.type).packageName, - "${service.name}${serviceSuffix}" - ) - ) + "${service.name}$serviceSuffix", + ), + ), ) .initializer(SERVICE_CONSTRUCTOR_ARGUMENT) .addModifiers(KModifier.PRIVATE) - .build() + .build(), ) } return builder @@ -158,7 +166,7 @@ object BindableAdapterGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { service.rpcs.forEach { rpc -> val serviceProviderName = if (options.singleMethodServices) { @@ -170,16 +178,25 @@ object BindableAdapterGenerator { val codeBlock = if (options.suspendingCalls) { when { !rpc.requestStreaming && !rpc.responseStreaming -> CodeBlock.of( - "return ${serviceProviderName}().${rpc.name}(request)" + "return $serviceProviderName().${rpc.name}(request)", ) !rpc.requestStreaming -> CodeBlock.of( - "return %T.serverStream(context, request, %L()::%L)", FlowAdapter::class, serviceProviderName, rpc.name + "return %T.serverStream(context, request, %L()::%L)", + FlowAdapter::class, + serviceProviderName, + rpc.name, ) !rpc.responseStreaming -> CodeBlock.of( - "return %T.clientStream(context, request, %L()::%L)", FlowAdapter::class, serviceProviderName, rpc.name + "return %T.clientStream(context, request, %L()::%L)", + FlowAdapter::class, + serviceProviderName, + rpc.name, ) else -> CodeBlock.of( - "return %T.bidiStream(context, request, %L()::%L)", FlowAdapter::class, serviceProviderName, rpc.name + "return %T.bidiStream(context, request, %L()::%L)", + FlowAdapter::class, + serviceProviderName, + rpc.name, ) } } else { @@ -189,40 +206,44 @@ object BindableAdapterGenerator { """ |val requestStream = %T() |streamExecutor.submit { - | ${serviceProviderName}().${rpc.name}(requestStream, %T(response)) + | $serviceProviderName().${rpc.name}(requestStream, %T(response)) |} |return requestStream - |""".trimMargin(), + | + """.trimMargin(), ClassName("com.squareup.wire.kotlin.grpcserver", "MessageSourceAdapter") .parameterizedBy(generator.classNameFor(rpc.requestType!!)), - responseAdapter + responseAdapter, ) rpc.requestStreaming -> CodeBlock.of( """ |val requestStream = %T() |streamExecutor.submit { - | response.onNext(${serviceProviderName}().${rpc.name}(requestStream)) + | response.onNext($serviceProviderName().${rpc.name}(requestStream)) | response.onCompleted() |} |return requestStream - |""".trimMargin(), + | + """.trimMargin(), ClassName("com.squareup.wire.kotlin.grpcserver", "MessageSourceAdapter") - .parameterizedBy(generator.classNameFor(rpc.requestType!!)) + .parameterizedBy(generator.classNameFor(rpc.requestType!!)), ) rpc.responseStreaming -> CodeBlock.of( """ - |${serviceProviderName}().${rpc.name}(request, %T(response)) - |""".trimMargin(), - responseAdapter + |$serviceProviderName().${rpc.name}(request, %T(response)) + | + """.trimMargin(), + responseAdapter, ) else -> CodeBlock.of( """ - |response.onNext(${serviceProviderName}().${rpc.name}(request)) + |response.onNext($serviceProviderName().${rpc.name}(request)) |response.onCompleted() - |""".trimMargin() + | + """.trimMargin(), ) } } @@ -232,7 +253,7 @@ object BindableAdapterGenerator { .apply { addImplBaseRpcSignature(generator, this, rpc, options) } .apply { if (options.suspendingCalls && !rpc.responseStreaming) { addModifiers(KModifier.SUSPEND) } } .addCode(codeBlock) - .build() + .build(), ) } return builder diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BlockingStubGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BlockingStubGenerator.kt index 1e6ee0bb46..f8c9636d26 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BlockingStubGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/BlockingStubGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -31,14 +31,14 @@ object BlockingStubGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { if (!options.suspendingCalls) { val serviceClassName = generator.classNameFor(service.type) val stubClassName = ClassName( packageName = serviceClassName.packageName, "${serviceClassName.simpleName}WireGrpc", - "${serviceClassName.simpleName}BlockingStub" + "${serviceClassName.simpleName}BlockingStub", ) return builder .addFunction( @@ -46,14 +46,20 @@ object BlockingStubGenerator { .addParameter("channel", ClassName("io.grpc", "Channel")) .returns(stubClassName) .addCode("return %T(channel)", stubClassName) - .build() + .build(), ) .addType( TypeSpec.classBuilder(stubClassName) - .apply { addAbstractStubConstructor(generator, this, service, - ClassName("io.grpc.stub", "AbstractStub")) } + .apply { + addAbstractStubConstructor( + generator, + this, + service, + ClassName("io.grpc.stub", "AbstractStub"), + ) + } .addBlockingStubRpcCalls(generator, service) - .build() + .build(), ) } else { return builder @@ -68,15 +74,18 @@ object BlockingStubGenerator { "return %M(channel, get${rpc.name}Method(), callOptions, request)", MemberName( enclosingClassName = ClassName("io.grpc.stub", "ClientCalls"), - simpleName = if (rpc.requestStreaming) "blockingServerStreamingCall" - else "blockingUnaryCall" - ) + simpleName = if (rpc.requestStreaming) { + "blockingServerStreamingCall" + } else { + "blockingUnaryCall" + }, + ), ) this.addFunction( FunSpec.builder(rpc.name) .addBlockingStubSignature(generator, rpc) .addCode(codeBlock) - .build() + .build(), ) } return this @@ -85,9 +94,11 @@ object BlockingStubGenerator { private fun FunSpec.Builder.addBlockingStubSignature(generator: ClassNameGenerator, rpc: Rpc): FunSpec.Builder = this .addParameter("request", ClassName.bestGuess(generator.classNameFor(rpc.requestType!!).toString())) .returns( - if (rpc.requestStreaming) + if (rpc.requestStreaming) { Iterator::class.asClassName() .parameterizedBy(generator.classNameFor(rpc.responseType!!)) - else generator.classNameFor(rpc.responseType!!) + } else { + generator.classNameFor(rpc.responseType!!) + }, ) } diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ClassNameGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ClassNameGenerator.kt index d506790104..7d6ae2791d 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ClassNameGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ClassNameGenerator.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.kotlin.grpcserver import com.squareup.kotlinpoet.ClassName @@ -9,7 +24,7 @@ internal class ClassNameGenerator(private val typeToKotlinName: Map) { builder.addProperty( PropertySpec - .builder("descriptorMap", Map::class.parameterizedBy( - String::class, DescriptorProtos.FileDescriptorProto::class - ) + .builder( + "descriptorMap", + Map::class.parameterizedBy( + String::class, + DescriptorProtos.FileDescriptorProto::class, + ), ) .addModifiers(KModifier.PRIVATE) .initializer( @@ -86,8 +89,8 @@ object FileDescriptorGenerator { } }.addStatement(")),") } - }.addStatement(")").build() - ).build() + }.addStatement(")").build(), + ).build(), ) } @@ -104,8 +107,8 @@ object FileDescriptorGenerator { val proto = descriptorMap[path]!! val deps = proto.dependencyList.filter { !visited.contains(it) }.map { fileDescriptor(it, visited + path) } return Descriptors.FileDescriptor.buildFrom(proto, deps.toTypedArray()) - """.trimIndent() - ).build() + """.trimIndent(), + ).build(), ) } @@ -121,8 +124,8 @@ object FileDescriptorGenerator { val str = data.fold(java.lang.StringBuilder()) { b, s -> b.append(s) }.toString() val bytes = java.util.Base64.getDecoder().decode(str) return DescriptorProtos.FileDescriptorProto.parseFrom(bytes) - """.trimIndent() - ).build() + """.trimIndent(), + ).build(), ) } diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ImplBaseGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ImplBaseGenerator.kt index c843957467..19ad8b1e02 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ImplBaseGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ImplBaseGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -39,7 +39,7 @@ object ImplBaseGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ) = builder .addType( TypeSpec.classBuilder("${service.name}ImplBase") @@ -47,7 +47,7 @@ object ImplBaseGenerator { .addSuperinterface(WireBindableService::class) .apply { addImplBaseConstructor(options) } .apply { addImplBaseBody(generator, this, service, options) } - .build() + .build(), ) private fun TypeSpec.Builder.addImplBaseConstructor(options: KotlinGrpcGenerator.Companion.Options) { @@ -59,14 +59,14 @@ object ImplBaseGenerator { .defaultValue( CodeBlock.builder() .addStatement("kotlin.coroutines.EmptyCoroutineContext") - .build() - ).build() + .build(), + ).build(), ) - .build() + .build(), ).addProperty( PropertySpec.builder("context", CoroutineContext::class, KModifier.PROTECTED) .initializer("context") - .build() + .build(), ) } } @@ -75,7 +75,7 @@ object ImplBaseGenerator { generator: ClassNameGenerator, builder: FunSpec.Builder, rpc: Rpc, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): FunSpec.Builder { val rpcRequestType = generator.classNameFor(rpc.requestType!!) val rpcResponseType = generator.classNameFor(rpc.responseType!!) @@ -96,17 +96,19 @@ object ImplBaseGenerator { rpc.requestStreaming -> builder .addParameter( - "response", ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcResponseType) + "response", + ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcResponseType), ) .returns( - ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcRequestType) + ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcRequestType), ) else -> builder .addParameter("request", rpcRequestType) .addParameter( - "response", ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcResponseType) + "response", + ClassName("io.grpc.stub", "StreamObserver").parameterizedBy(rpcResponseType), ) .returns(UNIT) } @@ -117,7 +119,7 @@ object ImplBaseGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { service.rpcs.forEach { rpc -> builder.addFunction( @@ -126,7 +128,7 @@ object ImplBaseGenerator { .apply { addImplBaseRpcSignature(generator, this, rpc, options) } .apply { if (options.suspendingCalls && !rpc.responseStreaming) { addModifiers(KModifier.SUSPEND) } } .addCode(CodeBlock.of("throw %T()", UnsupportedOperationException::class.java)) - .build() + .build(), ) } @@ -135,7 +137,7 @@ object ImplBaseGenerator { .addModifiers(KModifier.OVERRIDE) .returns(ClassName("io.grpc", "ServerServiceDefinition")) .addCode(bindServiceCodeBlock(service, options)) - .build() + .build(), ) service.rpcs @@ -152,14 +154,14 @@ object ImplBaseGenerator { .addParameter(ParameterSpec(name = "value", type = className)) .returns(InputStream::class) .addCode(streamCodeFor(it, className)) - .build() + .build(), ) .addFunction( FunSpec.builder("marshalledClass") .addModifiers(KModifier.OVERRIDE) .returns(Class::class.asClassName().parameterizedBy(className)) .addCode(CodeBlock.of("return %T::class.java", className)) - .build() + .build(), ) .addFunction( FunSpec.builder("parse") @@ -167,9 +169,9 @@ object ImplBaseGenerator { .addParameter("stream", InputStream::class) .returns(className) .addCode(parseCodeFor(it, className)) - .build() + .build(), ) - .build() + .build(), ) } @@ -224,8 +226,8 @@ object ImplBaseGenerator { implementation = this@${service.name}ImplBase::${it.name}, ) ) - """.trimIndent(), - MemberName(ClassName("io.grpc.stub", "ServerCalls"), bindServiceCallType(it)) + """.trimIndent(), + MemberName(ClassName("io.grpc.stub", "ServerCalls"), bindServiceCallType(it)), ) } else { codeBlock.add( @@ -233,8 +235,8 @@ object ImplBaseGenerator { get${it.name}Method(), %M(this@${service.name}ImplBase::${it.name}) ) - """.trimIndent(), - MemberName(ClassName("io.grpc.stub", "ServerCalls"), bindServiceCallType(it)) + """.trimIndent(), + MemberName(ClassName("io.grpc.stub", "ServerCalls"), bindServiceCallType(it)), ) } } diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGenerator.kt index 2694e89d94..8e7082ccdb 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -18,9 +18,9 @@ package com.squareup.wire.kotlin.grpcserver import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec +import com.squareup.wire.kotlin.grpcserver.BindableAdapterGenerator.addBindableAdapter import com.squareup.wire.kotlin.grpcserver.BlockingStubGenerator.addBlockingStub import com.squareup.wire.kotlin.grpcserver.ImplBaseGenerator.addImplBase -import com.squareup.wire.kotlin.grpcserver.BindableAdapterGenerator.addBindableAdapter import com.squareup.wire.kotlin.grpcserver.MethodDescriptorGenerator.addMethodDescriptor import com.squareup.wire.kotlin.grpcserver.ServiceDescriptorGenerator.addServiceDescriptor import com.squareup.wire.kotlin.grpcserver.StubGenerator.addStub @@ -33,7 +33,7 @@ class KotlinGrpcGenerator( private val typeToKotlinName: Map, private val singleMethodServices: Boolean, private val suspendingCalls: Boolean, - ) { +) { fun generateGrpcServer(service: Service, protoFile: ProtoFile?, schema: Schema): Pair { val options = Options( singleMethodServices = singleMethodServices, diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorGenerator.kt index 87a7707066..69acc27bfa 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -30,7 +30,7 @@ object MethodDescriptorGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - rpc: Rpc + rpc: Rpc, ): TypeSpec.Builder { val requestType = generator.classNameFor(rpc.requestType!!) val responseType = generator.classNameFor(rpc.responseType!!) @@ -39,32 +39,32 @@ object MethodDescriptorGenerator { PropertySpec.builder( name = "get${rpc.name}Method", type = methodDescriptorType(requestType, responseType).copy(nullable = true), - modifiers = listOf(KModifier.PRIVATE) + modifiers = listOf(KModifier.PRIVATE), ) .mutable(true) .addAnnotation(Volatile::class) .initializer("null") - .build() + .build(), ) .addFunction( FunSpec.builder("get${rpc.name}Method") .returns(methodDescriptorType(requestType, responseType)) .addCode(methodDescriptorCodeBlock(generator, service, rpc)) - .build() + .build(), ) } private fun methodDescriptorCodeBlock( generator: ClassNameGenerator, service: Service, - rpc: Rpc + rpc: Rpc, ): CodeBlock { val requestType = generator.classNameFor(rpc.requestType!!) val responseType = generator.classNameFor(rpc.responseType!!) val codeBlock = CodeBlock.builder() codeBlock.addStatement( "var result: %T = get${rpc.name}Method", - methodDescriptorType(requestType, responseType).copy(nullable = true) + methodDescriptorType(requestType, responseType).copy(nullable = true), ) codeBlock.add( """ @@ -89,14 +89,14 @@ object MethodDescriptorGenerator { return get${rpc.name}Method!! """.trimIndent(), requestType, - responseType + responseType, ) return codeBlock.build() } private fun methodDescriptorType( requestType: ClassName, - responseType: ClassName + responseType: ClassName, ) = ClassName("io.grpc", "MethodDescriptor").parameterizedBy(requestType, responseType) private fun methodType(rpc: Rpc): String = when { diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorGenerator.kt index e42b256ea0..adda6eb6a2 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -37,10 +37,10 @@ object ServiceDescriptorGenerator { PropertySpec.builder( name = "SERVICE_NAME", type = String::class, - modifiers = emptyList() + modifiers = emptyList(), ) .initializer("\"${service.type}\"") - .build() + .build(), ) .addProperty( PropertySpec.builder( @@ -51,14 +51,14 @@ object ServiceDescriptorGenerator { .addAnnotation(Volatile::class) .initializer("null") .mutable(true) - .build() + .build(), ) .apply { FileDescriptorGenerator.addDescriptorDataProperty(this, protoFile, schema) } .addFunction( FunSpec.builder("getServiceDescriptor") .returns(ClassName("io.grpc", "ServiceDescriptor").copy(nullable = true)) .addCode(serviceDescriptorCodeBlock(service, protoFile)) - .build() + .build(), ) private fun serviceDescriptorCodeBlock(service: Service, protoFile: ProtoFile?): CodeBlock { @@ -82,15 +82,17 @@ object ServiceDescriptorGenerator { "result = %M(SERVICE_NAME)", MemberName( enclosingClassName = ClassName("io.grpc", "ServiceDescriptor"), - simpleName = "newBuilder" - ) + simpleName = "newBuilder", + ), ) service.rpcs.forEach { builder.addStatement(".addMethod(get${it.name}Method())") } - if (protoFile != null){ - builder.addStatement(""" + if (protoFile != null) { + builder.addStatement( + """ .setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier { fileDescriptor("${protoFile.location.path}", emptySet()) - })""".trimIndent() + }) + """.trimIndent(), ) } builder diff --git a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/StubGenerator.kt b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/StubGenerator.kt index 7f254d0286..c98edd8ad1 100644 --- a/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/StubGenerator.kt +++ b/wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/StubGenerator.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,8 +15,13 @@ */ package com.squareup.wire.kotlin.grpcserver -import com.squareup.kotlinpoet.* +import com.squareup.kotlinpoet.ClassName +import com.squareup.kotlinpoet.CodeBlock +import com.squareup.kotlinpoet.FunSpec +import com.squareup.kotlinpoet.KModifier +import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy +import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.kotlin.grpcserver.ImplBaseGenerator.addImplBaseRpcSignature import com.squareup.wire.schema.Rpc import com.squareup.wire.schema.Service @@ -26,7 +31,7 @@ object StubGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { return if (options.suspendingCalls) { suspendedStubs(generator, service, builder, options) @@ -39,12 +44,13 @@ object StubGenerator { generator: ClassNameGenerator, service: Service, builder: TypeSpec.Builder, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { val serviceClassName = generator.classNameFor(service.type) val stubClassName = ClassName( packageName = serviceClassName.packageName, - "${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub" + "${serviceClassName.simpleName}WireGrpc", + "${serviceClassName.simpleName}Stub", ) return builder .addFunction( @@ -52,16 +58,20 @@ object StubGenerator { .addParameter("channel", ClassName("io.grpc", "Channel")) .returns(stubClassName) .addCode("return %T(channel)", stubClassName) - .build() + .build(), ) .addType( TypeSpec.classBuilder(stubClassName) .apply { - addAbstractStubConstructor(generator, this, service, - ClassName("io.grpc.kotlin", "AbstractCoroutineStub")) + addAbstractStubConstructor( + generator, + this, + service, + ClassName("io.grpc.kotlin", "AbstractCoroutineStub"), + ) addSuspendedStubRpcCalls(generator, this, service, options) } - .build() + .build(), ) } @@ -69,12 +79,13 @@ object StubGenerator { generator: ClassNameGenerator, service: Service, builder: TypeSpec.Builder, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { val serviceClassName = generator.classNameFor(service.type) val stubClassName = ClassName( packageName = serviceClassName.packageName, - "${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub" + "${serviceClassName.simpleName}WireGrpc", + "${serviceClassName.simpleName}Stub", ) return builder .addFunction( @@ -82,7 +93,7 @@ object StubGenerator { .addParameter("channel", ClassName("io.grpc", "Channel")) .returns(stubClassName) .addCode("return %T(channel)", stubClassName) - .build() + .build(), ) .addType( TypeSpec.classBuilder(stubClassName) @@ -90,7 +101,7 @@ object StubGenerator { addAbstractStubConstructor(generator, this, service, ClassName("io.grpc.stub", "AbstractStub")) addStubRpcCalls(generator, this, service, options) } - .build() + .build(), ) } @@ -98,12 +109,13 @@ object StubGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - superClass: ClassName + superClass: ClassName, ): TypeSpec.Builder { val serviceClassName = generator.classNameFor(service.type) val stubClassName = ClassName( packageName = serviceClassName.packageName, - "${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub" + "${serviceClassName.simpleName}WireGrpc", + "${serviceClassName.simpleName}Stub", ) return builder // Really this is a superclass, just want to add secondary constructors. @@ -113,7 +125,7 @@ object StubGenerator { .addModifiers(KModifier.INTERNAL) .addParameter("channel", ClassName("io.grpc", "Channel")) .callSuperConstructor("channel") - .build() + .build(), ) .addFunction( FunSpec.constructorBuilder() @@ -121,7 +133,7 @@ object StubGenerator { .addParameter("channel", ClassName("io.grpc", "Channel")) .addParameter("callOptions", ClassName("io.grpc", "CallOptions")) .callSuperConstructor("channel", "callOptions") - .build() + .build(), ) .addFunction( FunSpec.builder("build") @@ -130,7 +142,7 @@ object StubGenerator { .addParameter("callOptions", ClassName("io.grpc", "CallOptions")) .addStatement("return ${service.name}Stub(channel, callOptions)") .returns(ClassName("", "${service.name}Stub")) - .build() + .build(), ) } @@ -138,26 +150,26 @@ object StubGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { service.rpcs.forEach { rpc -> val codeBlock = when { rpc.requestStreaming -> CodeBlock.of( "return %M(channel.newCall(get${rpc.name}Method(), callOptions), response)", - MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc)) + MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc)), ) else -> CodeBlock.of( "%M(channel.newCall(get${rpc.name}Method(), callOptions), request, response)", - MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc)) + MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc)), ) } builder.addFunction( FunSpec.builder(rpc.name) .apply { addImplBaseRpcSignature(generator, this, rpc, options) } .addCode(codeBlock) - .build() + .build(), ) } return builder @@ -167,19 +179,19 @@ object StubGenerator { generator: ClassNameGenerator, builder: TypeSpec.Builder, service: Service, - options: KotlinGrpcGenerator.Companion.Options + options: KotlinGrpcGenerator.Companion.Options, ): TypeSpec.Builder { service.rpcs.forEach { rpc -> val codeBlock = CodeBlock.of( "return %M(channel, get${rpc.name}Method(), request, callOptions)", - MemberName(ClassName("io.grpc.kotlin", "ClientCalls"), suspendedClientCallType(rpc)) + MemberName(ClassName("io.grpc.kotlin", "ClientCalls"), suspendedClientCallType(rpc)), ) builder.addFunction( FunSpec.builder(rpc.name) .apply { addImplBaseRpcSignature(generator, this, rpc, options) } .addModifiers(KModifier.SUSPEND) .addCode(codeBlock) - .build() + .build(), ) } return builder diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterTest.kt index c7a91584b2..7d1071b732 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/BindableAdapterTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -19,14 +19,10 @@ import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.buildSchema import com.squareup.wire.kotlin.grpcserver.BindableAdapterGenerator.addBindableAdapter -import com.squareup.wire.schema.addLocal import com.squareup.wire.kotlin.grpcserver.GoldenTestUtils.assertFileEquals -import java.io.File +import com.squareup.wire.schema.addLocal import kotlin.test.assertEquals import okio.Path.Companion.toPath -import okio.buffer -import okio.source -import org.assertj.core.api.Assertions import org.junit.Test class BindableAdapterTest { @@ -47,7 +43,7 @@ class BindableAdapterTest { KotlinGrpcGenerator.Companion.Options(singleMethodServices = true, suspendingCalls = false), ) } - .build() + .build(), ) .build() @@ -56,7 +52,10 @@ class BindableAdapterTest { @Test fun `works on suspending streaming responses`() { - val code = bindableCodeFor("test", "TestService", """ + val code = bindableCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -64,8 +63,10 @@ class BindableAdapterTest { service TestService { rpc TestRPC(Test) returns (stream Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import com.squareup.wire.kotlin.grpcserver.FlowAdapter @@ -79,12 +80,17 @@ class BindableAdapterTest { service()::TestRPC) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } @Test fun `works on suspending streaming requests`() { - val code = bindableCodeFor("test", "TestService", """ + val code = bindableCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -92,8 +98,10 @@ class BindableAdapterTest { service TestService { rpc TestRPC(stream Test) returns (Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import com.squareup.wire.kotlin.grpcserver.FlowAdapter @@ -107,12 +115,17 @@ class BindableAdapterTest { request, service()::TestRPC) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } @Test fun `works on suspending streaming bidi rpcs`() { - val code = bindableCodeFor("test", "TestService", """ + val code = bindableCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -120,8 +133,10 @@ class BindableAdapterTest { service TestService { rpc TestRPC(stream Test) returns (stream Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import com.squareup.wire.kotlin.grpcserver.FlowAdapter @@ -135,12 +150,17 @@ class BindableAdapterTest { service()::TestRPC) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } @Test fun `works on suspending streaming bidi rpcs with single method services`() { - val code = bindableCodeFor("test", "TestService", """ + val code = bindableCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -148,11 +168,14 @@ class BindableAdapterTest { service TestService { rpc TestRPC(stream Test) returns (stream Test){} } - """.trimMargin(), KotlinGrpcGenerator.Companion.Options( - singleMethodServices = true, - suspendingCalls = true - )) - assertEquals(""" + """.trimMargin(), + KotlinGrpcGenerator.Companion.Options( + singleMethodServices = true, + suspendingCalls = true, + ), + ) + assertEquals( + """ package test import com.squareup.wire.kotlin.grpcserver.FlowAdapter @@ -166,14 +189,20 @@ class BindableAdapterTest { TestRPC()::TestRPC) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } - private fun bindableCodeFor(pkg: String, serviceName: String, schemaCode: String, - options: KotlinGrpcGenerator.Companion.Options = KotlinGrpcGenerator.Companion.Options( - singleMethodServices = false, - suspendingCalls = true - )): String { + private fun bindableCodeFor( + pkg: String, + serviceName: String, + schemaCode: String, + options: KotlinGrpcGenerator.Companion.Options = KotlinGrpcGenerator.Companion.Options( + singleMethodServices = false, + suspendingCalls = true, + ), + ): String { val schema = buildSchema { add("test.proto".toPath(), schemaCode) } val service = schema.getService("$pkg.$serviceName")!! val typeSpec = TypeSpec.classBuilder("${serviceName}WireGrpc") @@ -188,4 +217,3 @@ class BindableAdapterTest { .trim() } } - diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/FileDescriptorGeneratorTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/FileDescriptorGeneratorTest.kt index 3b634b00fd..d5dac74168 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/FileDescriptorGeneratorTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/FileDescriptorGeneratorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -24,11 +24,11 @@ import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.buildSchema import com.squareup.wire.schema.Pruner import com.squareup.wire.schema.PruningRules -import okio.Path.Companion.toPath -import org.junit.Test import javax.script.ScriptEngineManager import kotlin.test.assertEquals +import okio.Path.Companion.toPath import org.assertj.core.api.Assertions +import org.junit.Test internal class FileDescriptorGeneratorTest { private data class Schema(val path: String, val content: String) @@ -38,31 +38,36 @@ internal class FileDescriptorGeneratorTest { val descriptor = descriptorFor( "test.proto", PruningRules.Builder(), - Schema("test.proto", - """ + Schema( + "test.proto", + """ |syntax = "proto2"; | |package test; |import "imported.proto"; | |message Test {} - |""".trimMargin() - ), Schema( - "imported.proto", - """ + | + """.trimMargin(), + ), + Schema( + "imported.proto", + """ |syntax = "proto2"; | |package test; | |message Imported {} - |""".trimMargin() - )) + | + """.trimMargin(), + ), + ) assertEquals("test", descriptor.`package`) assertEquals("test.proto", descriptor.name) assertEquals(descriptor.messageTypes.size, 1) assertEquals("Test", descriptor.messageTypes.first().name) - assertEquals( 1, descriptor.dependencies.size) + assertEquals(1, descriptor.dependencies.size) } @Test @@ -70,8 +75,9 @@ internal class FileDescriptorGeneratorTest { val descriptor = descriptorFor( "test.proto", PruningRules.Builder().addRoot("test.Caller"), - Schema("test.proto", - """ + Schema( + "test.proto", + """ |syntax = "proto2"; |package test; | @@ -85,8 +91,10 @@ internal class FileDescriptorGeneratorTest { |message Caller { | optional Test.Nested field = 1; |} - |""".trimMargin() - )) + | + """.trimMargin(), + ), + ) Assertions.assertThat(descriptor.toProto()).isEqualTo( DescriptorProtos.FileDescriptorProto.newBuilder() @@ -97,22 +105,24 @@ internal class FileDescriptorGeneratorTest { .setName("Test") .addEnumType( DescriptorProtos.EnumDescriptorProto.newBuilder() - .setName("Nested") - .addValue(0, DescriptorProtos.EnumValueDescriptorProto.newBuilder().setName("NESTED_UNDEFINED").setNumber(0)) - .addValue(1, DescriptorProtos.EnumValueDescriptorProto.newBuilder().setName("NESTED_DEFINED").setNumber(1)) - ) + .setName("Nested") + .addValue(0, DescriptorProtos.EnumValueDescriptorProto.newBuilder().setName("NESTED_UNDEFINED").setNumber(0)) + .addValue(1, DescriptorProtos.EnumValueDescriptorProto.newBuilder().setName("NESTED_DEFINED").setNumber(1)), + ), ) - .addMessageType(DescriptorProtos.DescriptorProto.newBuilder() - .setName("Caller") - .addField(DescriptorProtos.FieldDescriptorProto.newBuilder() - .setName("field") - .setNumber(1) - .setTypeName(".test.Test.Nested") - .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_ENUM) - .setLabel(Label.LABEL_OPTIONAL) - ) + .addMessageType( + DescriptorProtos.DescriptorProto.newBuilder() + .setName("Caller") + .addField( + DescriptorProtos.FieldDescriptorProto.newBuilder() + .setName("field") + .setNumber(1) + .setTypeName(".test.Test.Nested") + .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_ENUM) + .setLabel(Label.LABEL_OPTIONAL), + ), ) - .build() + .build(), ) } @@ -126,13 +136,16 @@ internal class FileDescriptorGeneratorTest { val pruned = pruner.prune() val protoFile = pruned.protoFile(schemas.first().path.toPath()) val file = FileSpec.scriptBuilder("test", "test.kts") - .addType(TypeSpec.classBuilder("Test") - .apply { FileDescriptorGenerator.addDescriptorDataProperty(this, protoFile, pruned) } - .addFunction(FunSpec.builder("output") - .returns(Descriptors.FileDescriptor::class) - .addCode("return fileDescriptor(\"$fileName\", emptySet())") - .build()) - .build() + .addType( + TypeSpec.classBuilder("Test") + .apply { FileDescriptorGenerator.addDescriptorDataProperty(this, protoFile, pruned) } + .addFunction( + FunSpec.builder("output") + .returns(Descriptors.FileDescriptor::class) + .addCode("return fileDescriptor(\"$fileName\", emptySet())") + .build(), + ) + .build(), ).addCode("Test().output()").build() val engine = ScriptEngineManager().getEngineByExtension("kts") diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GoldenTestUtils.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GoldenTestUtils.kt index 48486812a1..eb720a238f 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GoldenTestUtils.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GoldenTestUtils.kt @@ -5,7 +5,7 @@ * 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 + * https://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, diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GrpcGeneratorHelpers.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GrpcGeneratorHelpers.kt index 06e08567ab..7b99589ecb 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GrpcGeneratorHelpers.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/GrpcGeneratorHelpers.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.kotlin.grpcserver import com.squareup.kotlinpoet.ClassName @@ -19,13 +34,13 @@ internal fun buildClassMap(schema: Schema, service: Service): Map + types: List, ): List> { return types.map { type -> val className = enclosingClassName?.nestedClass(type.type.simpleName) diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ImplBaseTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ImplBaseTest.kt index 35fabcd0c9..08c5f4d461 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ImplBaseTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ImplBaseTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -39,11 +39,11 @@ class ImplBaseTest { service = service, options = KotlinGrpcGenerator.Companion.Options( singleMethodServices = false, - suspendingCalls = false - ) + suspendingCalls = false, + ), ) } - .build() + .build(), ) .build() diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGeneratorTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGeneratorTest.kt index 5d982983de..83e5bbc48b 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGeneratorTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/KotlinGrpcGeneratorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -32,7 +32,7 @@ internal class KotlinGrpcGeneratorTest { val (_, typeSpec) = KotlinGrpcGenerator( buildClassMap(schema, service!!), singleMethodServices = true, - suspendingCalls = false + suspendingCalls = false, ).generateGrpcServer(service, schema.protoFile(path), schema) val output = FileSpec.get("routeguide", typeSpec) @@ -52,7 +52,8 @@ internal class KotlinGrpcGeneratorTest { | rpc Call1(Request) returns (Response) {} | rpc Call2(Request) returns (Response) {} |} - |""".trimMargin() + | + """.trimMargin() @Test fun `correctly generates singleMethodService = false adapters`() { @@ -62,7 +63,7 @@ internal class KotlinGrpcGeneratorTest { val (_, typeSpec) = KotlinGrpcGenerator( buildClassMap(schema, service!!), singleMethodServices = false, - suspendingCalls = false + suspendingCalls = false, ).generateGrpcServer(service, schema.protoFile(path), schema) val output = FileSpec.get("com.foo.bar", typeSpec) @@ -77,7 +78,7 @@ internal class KotlinGrpcGeneratorTest { val (_, typeSpec) = KotlinGrpcGenerator( buildClassMap(schema, service!!), singleMethodServices = true, - suspendingCalls = false + suspendingCalls = false, ).generateGrpcServer(service, schema.protoFile(path), schema) val output = FileSpec.get("com.foo.bar", typeSpec) @@ -87,19 +88,24 @@ internal class KotlinGrpcGeneratorTest { @Test fun `correctly generates adapters for Unit return values`() { val path = "service.proto".toPath() - val schema = buildSchema { add(path, """ + val schema = buildSchema { + add( + path, + """ syntax = "proto3"; import "google/protobuf/empty.proto"; service MyService { rpc doSomething(google.protobuf.Empty) returns (google.protobuf.Empty); } - """.trimIndent()) } + """.trimIndent(), + ) + } val service = schema.getService("MyService") val (_, typeSpec) = KotlinGrpcGenerator( buildClassMap(schema, service!!), singleMethodServices = false, - suspendingCalls = true + suspendingCalls = true, ).generateGrpcServer(service, schema.protoFile(path), schema) val output = FileSpec.get("", typeSpec) diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorTest.kt index c582d2fb20..7606fecb24 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/MethodDescriptorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -38,10 +38,10 @@ class MethodDescriptorTest { generator = ClassNameGenerator(buildClassMap(schema, service!!)), builder = this, service = service, - rpc = service.rpc("GetFeature")!! + rpc = service.rpc("GetFeature")!!, ) } - .build() + .build(), ) .build() diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorTest.kt index dc6b029d0e..710a3bde67 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/ServiceDescriptorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -36,7 +36,7 @@ class ServiceDescriptorTest { .apply { ServiceDescriptorGenerator.addServiceDescriptor(this, service!!, schema.protoFile(path), schema) } - .build() + .build(), ) .build() diff --git a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/StubTest.kt b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/StubTest.kt index 8c0af3eb87..5965267bb4 100644 --- a/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/StubTest.kt +++ b/wire-grpc-server-generator/src/test/java/com/squareup/wire/kotlin/grpcserver/StubTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -40,11 +40,11 @@ class StubTest { service, options = KotlinGrpcGenerator.Companion.Options( singleMethodServices = false, - suspendingCalls = false - ) + suspendingCalls = false, + ), ) } - .build() + .build(), ) .build() @@ -53,7 +53,10 @@ class StubTest { @Test fun `generates stubs for suspended bidi streaming rpc`() { - val code = stubCodeFor("test", "TestService", """ + val code = stubCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -61,8 +64,10 @@ class StubTest { service TestService { rpc TestRPC(stream Test) returns (stream Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import io.grpc.CallOptions @@ -86,12 +91,17 @@ class StubTest { getTestRPCMethod(), request, callOptions) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } @Test fun `generates stubs for suspended server streaming rpc`() { - val code = stubCodeFor("test", "TestService", """ + val code = stubCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -99,8 +109,10 @@ class StubTest { service TestService { rpc TestRPC(Test) returns (stream Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import io.grpc.CallOptions @@ -124,12 +136,17 @@ class StubTest { getTestRPCMethod(), request, callOptions) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } @Test fun `generates stubs for suspended client streaming rpc`() { - val code = stubCodeFor("test", "TestService", """ + val code = stubCodeFor( + "test", + "TestService", + """ syntax = "proto2"; package test; @@ -137,8 +154,10 @@ class StubTest { service TestService { rpc TestRPC(stream Test) returns (Test){} } - """.trimMargin()) - assertEquals(""" + """.trimMargin(), + ) + assertEquals( + """ package test import io.grpc.CallOptions @@ -162,14 +181,20 @@ class StubTest { getTestRPCMethod(), request, callOptions) } } - """.trimIndent().trim(), code) + """.trimIndent().trim(), + code, + ) } - private fun stubCodeFor(pkg: String, serviceName: String, schemaCode: String, - options: KotlinGrpcGenerator.Companion.Options = KotlinGrpcGenerator.Companion.Options( - singleMethodServices = false, - suspendingCalls = true - )): String { + private fun stubCodeFor( + pkg: String, + serviceName: String, + schemaCode: String, + options: KotlinGrpcGenerator.Companion.Options = KotlinGrpcGenerator.Companion.Options( + singleMethodServices = false, + suspendingCalls = true, + ), + ): String { val schema = buildSchema { add("test.proto".toPath(), schemaCode) } val service = schema.getService("$pkg.$serviceName")!! val typeSpec = TypeSpec.classBuilder("${serviceName}WireGrpc") diff --git a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/FlowAdapter.kt b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/FlowAdapter.kt index a36898e2cc..7f83c96d81 100644 --- a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/FlowAdapter.kt +++ b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/FlowAdapter.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,6 +15,7 @@ */ package com.squareup.wire.kotlin.grpcserver +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel @@ -24,7 +25,6 @@ import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.launch -import kotlin.coroutines.CoroutineContext /** * This is an adapter class to convert Wire generated Channel based routines to @@ -35,7 +35,7 @@ object FlowAdapter { fun serverStream( context: CoroutineContext, request: I, - f: suspend (I, SendChannel) -> Unit + f: suspend (I, SendChannel) -> Unit, ): Flow { val sendChannel = Channel() @@ -46,7 +46,7 @@ object FlowAdapter { suspend fun clientStream( context: CoroutineContext, request: Flow, - f: suspend (ReceiveChannel) -> O + f: suspend (ReceiveChannel) -> O, ): O { val receiveChannel = Channel() @@ -61,7 +61,7 @@ object FlowAdapter { fun bidiStream( context: CoroutineContext, request: Flow, - f: suspend (ReceiveChannel, SendChannel) -> Unit + f: suspend (ReceiveChannel, SendChannel) -> Unit, ): Flow { val sendChannel = Channel() val receiveChannel = Channel() diff --git a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSinkAdapter.kt b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSinkAdapter.kt index 66762103b5..f0259387f8 100644 --- a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSinkAdapter.kt +++ b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSinkAdapter.kt @@ -5,7 +5,7 @@ * 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 + * https://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, diff --git a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSourceAdapter.kt b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSourceAdapter.kt index b9e27f0626..82864e2e3f 100644 --- a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSourceAdapter.kt +++ b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/MessageSourceAdapter.kt @@ -5,7 +5,7 @@ * 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 + * https://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, diff --git a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireBindableService.kt b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireBindableService.kt index 98f3d90fc9..4dfbac8258 100644 --- a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireBindableService.kt +++ b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireBindableService.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.kotlin.grpcserver import io.grpc.BindableService diff --git a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireMethodMarshaller.kt b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireMethodMarshaller.kt index 91184fd0fb..e06de4bd90 100644 --- a/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireMethodMarshaller.kt +++ b/wire-grpc-server/src/main/java/com/squareup/wire/kotlin/grpcserver/WireMethodMarshaller.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.kotlin.grpcserver import io.grpc.MethodDescriptor diff --git a/wire-grpc-tests/build.gradle.kts b/wire-grpc-tests/build.gradle.kts index 2a8b9aec7f..e2f59f7bdb 100644 --- a/wire-grpc-tests/build.gradle.kts +++ b/wire-grpc-tests/build.gradle.kts @@ -1,3 +1,4 @@ +import com.diffplug.gradle.spotless.SpotlessExtension import com.google.protobuf.gradle.generateProtoTasks import com.google.protobuf.gradle.id import com.google.protobuf.gradle.ofSourceSet @@ -79,3 +80,12 @@ val test by tasks.getting(Test::class) { exceptionFormat = TestExceptionFormat.FULL } } + +configure { + kotlin { + targetExclude( + // Generated files. + "src/test/proto-grpc/**/*.kt", + ) + } +} diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcCallsTest.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcCallsTest.kt index 94973562e1..0e3f652533 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcCallsTest.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcCallsTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -15,6 +15,7 @@ */ package com.squareup.wire +import java.util.concurrent.LinkedBlockingQueue import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.runBlocking @@ -22,7 +23,6 @@ import okio.IOException import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test -import java.util.concurrent.LinkedBlockingQueue @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi @@ -62,7 +62,7 @@ class GrpcCallsTest { override fun onSuccess(call: GrpcCall, response: String) { log.add("success: $response") } - } + }, ) assertThat(log.take()).isEqualTo("success: HELLO") @@ -115,7 +115,7 @@ class GrpcCallsTest { override fun onSuccess(call: GrpcCall, response: String) { log.add("success: $response") } - } + }, ) assertThat(log.take()) @@ -173,7 +173,7 @@ class GrpcCallsTest { override fun onSuccess(call: GrpcCall, response: String) { error("unexpected call") } - } + }, ) fail() } catch (e: IllegalStateException) { @@ -231,7 +231,7 @@ class GrpcCallsTest { override fun onSuccess(call: GrpcCall, response: String) { log.add("success: $response") } - } + }, ) assertThat(log.take()).isEqualTo("failure: java.io.IOException: canceled") diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt index b3d7c5bad6..cb350d3273 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -26,6 +26,10 @@ import com.squareup.wire.MockRouteGuideService.Action.SendMessage import io.grpc.Metadata import io.grpc.Status import io.grpc.StatusException +import java.io.IOException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi @@ -39,6 +43,8 @@ import okhttp3.Interceptor import okhttp3.Interceptor.Chain import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient +import okhttp3.Protocol.H2_PRIOR_KNOWLEDGE +import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_2 import okhttp3.Request import okhttp3.Response @@ -48,6 +54,7 @@ import okio.Buffer import okio.ByteString import org.assertj.core.api.Assertions.assertThat import org.junit.After +import org.junit.Assert.assertThrows import org.junit.Assert.fail import org.junit.Before import org.junit.Ignore @@ -61,19 +68,15 @@ import routeguide.RouteGuideClient import routeguide.RouteGuideProto import routeguide.RouteNote import routeguide.RouteSummary -import java.io.IOException -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicReference -import okhttp3.Protocol.H2_PRIOR_KNOWLEDGE -import okhttp3.Protocol.HTTP_1_1 -import org.junit.Assert.assertThrows @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class GrpcClientTest { - @JvmField @Rule val mockService = MockRouteGuideService() - @JvmField @Rule val timeout = Timeout(30, TimeUnit.SECONDS) + @JvmField @Rule + val mockService = MockRouteGuideService() + + @JvmField @Rule + val timeout = Timeout(30, TimeUnit.SECONDS) private lateinit var okhttpClient: OkHttpClient private lateinit var grpcClient: GrpcClient @@ -118,7 +121,7 @@ class GrpcClientTest { } assertThat(exception.message) .isEqualTo( - "OkHttpClient is not configured with a HTTP/2 protocol which is required for gRPC connections." + "OkHttpClient is not configured with a HTTP/2 protocol which is required for gRPC connections.", ) } @@ -214,7 +217,7 @@ class GrpcClientTest { feature = response latch.countDown() } - } + }, ) mockService.awaitSuccessBlocking() @@ -886,7 +889,7 @@ class GrpcClientTest { feature = response latch.countDown() } - } + }, ) assertThat(grpcCall.isExecuted()).isTrue() @@ -949,7 +952,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)", ) } } @@ -970,7 +973,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)", ) } } @@ -991,7 +994,7 @@ class GrpcClientTest { object : GrpcCall.Callback { override fun onFailure(call: GrpcCall, exception: IOException) { assertThat(exception).hasMessage( - "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)", ) latch.countDown() } @@ -999,7 +1002,7 @@ class GrpcClientTest { override fun onSuccess(call: GrpcCall, response: Feature) { throw AssertionError() } - } + }, ) mockService.awaitSuccessBlocking() @@ -1027,7 +1030,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "expected gRPC but was HTTP status=500, content-type=application/grpc" + "expected gRPC but was HTTP status=500, content-type=application/grpc", ) } } @@ -1054,7 +1057,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "expected gRPC but was HTTP status=200, content-type=text/plain" + "expected gRPC but was HTTP status=200, content-type=text/plain", ) } } @@ -1151,7 +1154,7 @@ class GrpcClientTest { } catch (expected: GrpcException) { assertThat(expected.grpcStatus).isEqualTo(GrpcStatus.INTERNAL) assertThat(expected).hasMessage( - "grpc-status=13, grpc-status-name=INTERNAL, grpc-message=boom" + "grpc-status=13, grpc-status-name=INTERNAL, grpc-message=boom", ) } } @@ -1172,7 +1175,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)", ) assertThat(expected.cause).hasMessage("stream was reset: CANCEL") } @@ -1197,7 +1200,7 @@ class GrpcClientTest { // It's racy whether we receive trailers first or close the response stream first. assertThat(expected.message).isIn( "gRPC transport failure (HTTP status=200, grpc-status=0, grpc-message=null)", - "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=null, grpc-message=null)", ) assertThat(expected.cause).hasMessage("expected 1 message but got multiple") } @@ -1217,7 +1220,7 @@ class GrpcClientTest { fail() } catch (expected: IOException) { assertThat(expected).hasMessage( - "gRPC transport failure (HTTP status=200, grpc-status=0, grpc-message=null)" + "gRPC transport failure (HTTP status=200, grpc-status=0, grpc-message=null)", ) assertThat(expected.cause).hasMessage("expected 1 message but got none") } @@ -1338,7 +1341,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/GetFeature", requestHeaders = mapOf("request-lucky-number" to "twenty-two"), - ) + ), ) mockService.enqueueReceivePoint(latitude = 5, longitude = 6) mockService.enqueue(ReceiveComplete) @@ -1347,8 +1350,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("tree at 5,6") .build(), - responseHeaders = mapOf("response-lucky-animal" to "horse") - ) + responseHeaders = mapOf("response-lucky-animal" to "horse"), + ), ) mockService.enqueue(SendCompleted) @@ -1368,7 +1371,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/GetFeature", requestHeaders = mapOf("request-lucky-number" to "twenty-two"), - ) + ), ) mockService.enqueueReceivePoint(latitude = 5, longitude = 6) mockService.enqueue(ReceiveComplete) @@ -1377,8 +1380,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("tree at 5,6") .build(), - responseHeaders = mapOf("response-lucky-animal" to "horse") - ) + responseHeaders = mapOf("response-lucky-animal" to "horse"), + ), ) mockService.enqueue(SendCompleted) // Cloned call. @@ -1386,7 +1389,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/GetFeature", requestHeaders = mapOf("request-lucky-number" to "twenty-two", "all-in" to "true"), - ) + ), ) mockService.enqueueReceivePoint(latitude = 15, longitude = 16) mockService.enqueue(ReceiveComplete) @@ -1395,8 +1398,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("tree at 15,16") .build(), - responseHeaders = mapOf("response-lucky-animal" to "emu") - ) + responseHeaders = mapOf("response-lucky-animal" to "emu"), + ), ) mockService.enqueue(SendCompleted) @@ -1425,7 +1428,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/ListFeatures", requestHeaders = mapOf("request-lucky-number" to "twenty-two"), - ) + ), ) mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5)) mockService.enqueue(ReceiveComplete) @@ -1434,8 +1437,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("tree") .build(), - responseHeaders = mapOf("response-lucky-animal" to "horse") - ) + responseHeaders = mapOf("response-lucky-animal" to "horse"), + ), ) mockService.enqueueSendFeature(name = "house") mockService.enqueue(SendCompleted) @@ -1459,7 +1462,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/ListFeatures", requestHeaders = mapOf("request-lucky-number" to "twenty-two"), - ) + ), ) mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(4, 5)) mockService.enqueue(ReceiveComplete) @@ -1468,8 +1471,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("tree") .build(), - responseHeaders = mapOf("response-lucky-animal" to "horse") - ) + responseHeaders = mapOf("response-lucky-animal" to "horse"), + ), ) mockService.enqueueSendFeature(name = "house") mockService.enqueue(SendCompleted) @@ -1478,7 +1481,7 @@ class GrpcClientTest { ReceiveCall( path = "/routeguide.RouteGuide/ListFeatures", requestHeaders = mapOf("request-lucky-number" to "twenty-two", "all-in" to "true"), - ) + ), ) mockService.enqueueReceiveRectangle(lo = Point(0, 0), hi = Point(14, 15)) mockService.enqueue(ReceiveComplete) @@ -1487,8 +1490,8 @@ class GrpcClientTest { message = RouteGuideProto.Feature.newBuilder() .setName("forest") .build(), - responseHeaders = mapOf("response-lucky-animal" to "emu") - ) + responseHeaders = mapOf("response-lucky-animal" to "emu"), + ), ) mockService.enqueueSendFeature(name = "cabane") mockService.enqueue(SendCompleted) @@ -1572,7 +1575,7 @@ class GrpcClientTest { val metadata = Metadata().apply { put( Metadata.Key.of("grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER), - RouteNote(message = "marco").encode() + RouteNote(message = "marco").encode(), ) } mockService.enqueueSendError(Status.INTERNAL.withDescription("boom").asRuntimeException(metadata)) @@ -1634,15 +1637,15 @@ class GrpcClientTest { } class IncompatibleRouteGuideClient( - private val client: GrpcClient + private val client: GrpcClient, ) { fun RouteChat(): GrpcCall = client.newCall( GrpcMethod( path = "/routeguide.RouteGuide/RouteChat", requestAdapter = RouteNote.ADAPTER, - responseAdapter = RouteNote.ADAPTER - ) + responseAdapter = RouteNote.ADAPTER, + ), ) } } diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcOnMockWebServerTest.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcOnMockWebServerTest.kt index 85a7cbf8f4..6ec495fa2d 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcOnMockWebServerTest.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcOnMockWebServerTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -16,6 +16,8 @@ package com.squareup.wire import com.squareup.wire.mockwebserver.GrpcDispatcher +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.runBlocking @@ -35,14 +37,15 @@ import routeguide.Rectangle import routeguide.RouteGuideClient import routeguide.RouteNote import routeguide.RouteSummary -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicReference @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class GrpcOnMockWebServerTest { - @JvmField @Rule val mockWebServer = MockWebServer() - @JvmField @Rule val timeout = Timeout(30, TimeUnit.SECONDS) + @JvmField @Rule + val mockWebServer = MockWebServer() + + @JvmField @Rule + val timeout = Timeout(30, TimeUnit.SECONDS) private lateinit var okhttpClient: OkHttpClient private lateinit var grpcClient: GrpcClient @@ -59,7 +62,7 @@ class GrpcOnMockWebServerTest { fun setUp() { mockWebServer.dispatcher = GrpcDispatcher( services = listOf(fakeRouteGuide), - delegate = mockWebServer.dispatcher + delegate = mockWebServer.dispatcher, ) mockWebServer.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE) diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcStreamingCallsTest.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcStreamingCallsTest.kt index 2a676c8c9d..77a7086f2b 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcStreamingCallsTest.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcStreamingCallsTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt index 1ae1b7cbda..3bf67f3236 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -27,6 +27,8 @@ import io.grpc.ServerCall.Listener import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import io.grpc.stub.StreamObserver +import java.util.ArrayDeque +import java.util.concurrent.TimeUnit import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED @@ -43,8 +45,6 @@ import routeguide.RouteGuideProto.Point import routeguide.RouteGuideProto.Rectangle import routeguide.RouteGuideProto.RouteNote import routeguide.RouteGuideProto.RouteSummary -import java.util.ArrayDeque -import java.util.concurrent.TimeUnit /** * An assertive scriptable implementation of the [RouteGuideGrpc] gRPC service. Receiving and @@ -71,8 +71,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.ReceiveMessage( RouteNote.newBuilder() .setMessage(message) - .build() - ) + .build(), + ), ) } @@ -82,8 +82,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Point.newBuilder() .setLatitude(latitude) .setLongitude(longitude) - .build() - ) + .build(), + ), ) } @@ -93,8 +93,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Rectangle.newBuilder() .setLo(Point.newBuilder().setLatitude(lo.latitude!!).setLongitude(lo.longitude!!).build()) .setHi(Point.newBuilder().setLatitude(hi.latitude!!).setLongitude(hi.longitude!!).build()) - .build() - ) + .build(), + ), ) } @@ -103,8 +103,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.SendMessage( Feature.newBuilder() .setName(name) - .build() - ) + .build(), + ), ) } @@ -113,8 +113,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.SendMessage( RouteNote.newBuilder() .setMessage(message) - .build() - ) + .build(), + ), ) } @@ -123,8 +123,8 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.SendMessage( RouteSummary.newBuilder() .setPointCount(pointCount) - .build() - ) + .build(), + ), ) } @@ -168,7 +168,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.ReceiveCall( path = "/routeguide.RouteGuide/GetFeature", requestHeaders = takeLastRequestHeaders(it), - ) + ), ) } assertNextActionAndProcessScript { @@ -186,7 +186,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.ReceiveCall( path = "/routeguide.RouteGuide/RecordRoute", requestHeaders = takeLastRequestHeaders(it), - ) + ), ) } return createAssertingStreamObserver() @@ -199,7 +199,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.ReceiveCall( path = "/routeguide.RouteGuide/ListFeatures", requestHeaders = takeLastRequestHeaders(it), - ) + ), ) } assertNextActionAndProcessScript { @@ -217,7 +217,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser Action.ReceiveCall( path = "/routeguide.RouteGuide/RouteChat", requestHeaders = takeLastRequestHeaders(it), - ) + ), ) } return createAssertingStreamObserver() @@ -227,7 +227,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser override fun interceptCall( call: ServerCall, requestHeaders: Metadata, - next: ServerCallHandler + next: ServerCallHandler, ): Listener { lastRequestHeaders = requestHeaders return next.startCall( @@ -240,7 +240,7 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser super.sendHeaders(responseHeaders) } }, - requestHeaders + requestHeaders, ) } @@ -338,14 +338,14 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser sealed class Action { data class ReceiveCall( val path: String, - val requestHeaders: Map = mapOf() + val requestHeaders: Map = mapOf(), ) : Action() data class ReceiveMessage(val message: com.google.protobuf.Message) : Action() object ReceiveError : Action() object ReceiveComplete : Action() data class SendMessage( val message: com.google.protobuf.Message, - val responseHeaders: Map = mapOf() + val responseHeaders: Map = mapOf(), ) : Action() data class SendError(val throwable: Throwable) : Action() object SendCompleted : Action() diff --git a/wire-gson-support/build.gradle.kts b/wire-gson-support/build.gradle.kts index a4158d4006..2edacf1113 100644 --- a/wire-gson-support/build.gradle.kts +++ b/wire-gson-support/build.gradle.kts @@ -1,3 +1,4 @@ +import com.diffplug.gradle.spotless.SpotlessExtension import com.vanniktech.maven.publish.JavadocJar.Dokka import com.vanniktech.maven.publish.KotlinJvm import com.vanniktech.maven.publish.MavenPublishBaseExtension @@ -17,6 +18,21 @@ if (project.rootProject.name == "wire") { KotlinJvm(javadocJar = Dokka("dokkaGfm"), sourcesJar = true) ) } + + configure { + kotlin { + targetExclude( + // Generated files. + "src/test/java/**/*.kt", + ) + } + java { + targetExclude( + // Generated files. + "src/test/java/**/*.java", + ) + } + } } dependencies { diff --git a/wire-gson-support/src/main/java/com/squareup/wire/AnyMessageTypeAdapter.kt b/wire-gson-support/src/main/java/com/squareup/wire/AnyMessageTypeAdapter.kt index 7ccf1d52dd..3ea20ae4df 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/AnyMessageTypeAdapter.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/AnyMessageTypeAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -25,7 +25,7 @@ import java.io.IOException class AnyMessageTypeAdapter( private val gson: Gson, - private val typeUrlToAdapter: Map> + private val typeUrlToAdapter: Map>, ) : TypeAdapter() { private val elementAdapter: TypeAdapter = gson.getAdapter(JsonElement::class.java) diff --git a/wire-gson-support/src/main/java/com/squareup/wire/EnumTypeAdapter.kt b/wire-gson-support/src/main/java/com/squareup/wire/EnumTypeAdapter.kt index 54400a2d1c..c753ee51ed 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/EnumTypeAdapter.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/EnumTypeAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt b/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt index a491c7f98d..781d3d4733 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -28,7 +28,7 @@ import java.lang.reflect.Type internal object GsonJsonIntegration : JsonIntegration>() { override fun frameworkAdapter( framework: Gson, - type: Type + type: Type, ): TypeAdapter = framework.getAdapter(TypeToken.get(type)).nullSafe() as TypeAdapter override fun listAdapter(elementAdapter: TypeAdapter): TypeAdapter = @@ -37,7 +37,7 @@ internal object GsonJsonIntegration : JsonIntegration>() override fun mapAdapter( framework: Gson, keyFormatter: JsonFormatter<*>, - valueAdapter: TypeAdapter + valueAdapter: TypeAdapter, ): TypeAdapter = MapJsonAdapter(keyFormatter, valueAdapter).nullSafe() as TypeAdapter fun TypeAdapter.serializeNulls(): TypeAdapter { @@ -67,7 +67,7 @@ internal object GsonJsonIntegration : JsonIntegration>() FormatterJsonAdapter(jsonFormatter).nullSafe() as TypeAdapter private class FormatterJsonAdapter( - private val formatter: JsonFormatter + private val formatter: JsonFormatter, ) : TypeAdapter() { override fun write(writer: JsonWriter, value: T) { val stringOrNumber = formatter.toStringOrNumber(value) @@ -90,7 +90,7 @@ internal object GsonJsonIntegration : JsonIntegration>() /** Adapt a list of values by delegating to an adapter for a single value. */ private class ListJsonAdapter( - private val single: TypeAdapter + private val single: TypeAdapter, ) : TypeAdapter>() { override fun read(reader: JsonReader): List { val result = mutableListOf() @@ -114,7 +114,7 @@ internal object GsonJsonIntegration : JsonIntegration>() /** Adapt a list of values by delegating to an adapter for a single value. */ private class MapJsonAdapter( private val keyFormatter: JsonFormatter, - private val valueAdapter: TypeAdapter + private val valueAdapter: TypeAdapter, ) : TypeAdapter>() { override fun read(reader: JsonReader): Map { val result = mutableMapOf() diff --git a/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt b/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt index 19c0b375c8..5344b43b63 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2013 Square Inc. + * Copyright (C) 2013 Square, Inc. * * 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 + * https://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, @@ -24,7 +24,7 @@ import java.io.IOException internal class MessageTypeAdapter, B : Message.Builder>( private val messageAdapter: RuntimeMessageAdapter, - private val jsonAdapters: List> + private val jsonAdapters: List>, ) : TypeAdapter() { private val nameToField = mutableMapOf>() .also { map -> @@ -45,7 +45,7 @@ internal class MessageTypeAdapter, B : Message.Builder>( messageAdapter.writeAllFields( message = message, jsonAdapters = jsonAdapters, - redactedFieldsAdapter = null + redactedFieldsAdapter = null, ) { name, value, jsonAdapter -> out.name(name) jsonAdapter.write(out, value) @@ -79,6 +79,6 @@ internal class MessageTypeAdapter, B : Message.Builder>( data class JsonField, B : Message.Builder>( val adapter: TypeAdapter, - val fieldBinding: FieldOrOneOfBinding + val fieldBinding: FieldOrOneOfBinding, ) } diff --git a/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt b/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt index 63adc5b799..f42212e174 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt @@ -1,11 +1,11 @@ /* - * Copyright 2013 Square Inc. + * Copyright (C) 2013 Square, Inc. * * 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 + * https://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, @@ -57,7 +57,7 @@ class WireTypeAdapterFactory @JvmOverloads constructor( val newMap = typeUrlToAdapter.toMutableMap() for (adapter in adapters) { val key = adapter.typeUrl ?: throw IllegalArgumentException( - "recompile ${adapter.type} to use it with WireTypeAdapterFactory" + "recompile ${adapter.type} to use it with WireTypeAdapterFactory", ) newMap[key] = adapter } diff --git a/wire-gson-support/src/test/java/com/squareup/wire/GsonNoAdapterTest.java b/wire-gson-support/src/test/java/com/squareup/wire/GsonNoAdapterTest.java index d8c89f5b20..565301b750 100644 --- a/wire-gson-support/src/test/java/com/squareup/wire/GsonNoAdapterTest.java +++ b/wire-gson-support/src/test/java/com/squareup/wire/GsonNoAdapterTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -15,6 +15,8 @@ */ package com.squareup.wire; +import static org.assertj.core.api.Assertions.assertThat; + import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.wire.proto2.dinosaurs.java.Dinosaur; @@ -25,33 +27,32 @@ import org.junit.Ignore; import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; - /** * Using Gson without the adapter is quite fragile: it leaks implementation details of how Gson * works, and it breaks on absent collection types. Nevertheless this is sufficiently commonplace * that we support it like it were a public API. */ public class GsonNoAdapterTest { - private final Gson gson = new GsonBuilder() - .disableHtmlEscaping() - .create(); + private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - @Test public void javaFullObject() { - Dinosaur value = new Dinosaur.Builder() - .name("Stegosaurus") - .period(Period.JURASSIC) - .length_meters(9.0) - .mass_kilograms(5_000.0) - .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) - .build(); - String json = "{" - + "\"name\":\"Stegosaurus\"," - + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]," - + "\"length_meters\":9.0," - + "\"mass_kilograms\":5000.0," - + "\"period\":\"JURASSIC\"" - + "}"; + @Test + public void javaFullObject() { + Dinosaur value = + new Dinosaur.Builder() + .name("Stegosaurus") + .period(Period.JURASSIC) + .length_meters(9.0) + .mass_kilograms(5_000.0) + .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) + .build(); + String json = + "{" + + "\"name\":\"Stegosaurus\"," + + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]," + + "\"length_meters\":9.0," + + "\"mass_kilograms\":5000.0," + + "\"period\":\"JURASSIC\"" + + "}"; assertThat(gson.toJson(value)).isEqualTo(json); Dinosaur decoded = gson.fromJson(json, Dinosaur.class); assertThat(decoded).isEqualTo(value); @@ -59,12 +60,10 @@ public class GsonNoAdapterTest { assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void javaListsOnly() { - Dinosaur value = new Dinosaur.Builder() - .build(); - String json = "{" - + "\"picture_urls\":[]" - + "}"; + @Test + public void javaListsOnly() { + Dinosaur value = new Dinosaur.Builder().build(); + String json = "{" + "\"picture_urls\":[]" + "}"; assertThat(gson.toJson(value)).isEqualTo(json); Dinosaur decoded = gson.fromJson(json, Dinosaur.class); assertThat(decoded).isEqualTo(value); @@ -73,9 +72,9 @@ public class GsonNoAdapterTest { } @Ignore("Absent lists are initialized to null in Java.") - @Test public void javaEmptyObject() { - Dinosaur value = new Dinosaur.Builder() - .build(); + @Test + public void javaEmptyObject() { + Dinosaur value = new Dinosaur.Builder().build(); String json = "{}"; assertThat(gson.toJson(value)).isEqualTo("{\"picture_urls\":[]}"); Dinosaur decoded = gson.fromJson(json, Dinosaur.class); @@ -84,54 +83,60 @@ public class GsonNoAdapterTest { assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void interopFullObject() { + @Test + public void interopFullObject() { com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur value = new com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.Builder() - .name("Stegosaurus") - .period(com.squareup.wire.proto2.geology.javainteropkotlin.Period.JURASSIC) - .length_meters(9.0) - .mass_kilograms(5_000.0) - .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) - .build(); - String json = "{" - + "\"name\":\"Stegosaurus\"," - + "\"length_meters\":9.0," - + "\"mass_kilograms\":5000.0," - + "\"period\":\"JURASSIC\"," - + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]" - + "}"; + .name("Stegosaurus") + .period(com.squareup.wire.proto2.geology.javainteropkotlin.Period.JURASSIC) + .length_meters(9.0) + .mass_kilograms(5_000.0) + .picture_urls(Arrays.asList("http://goo.gl/LD5KY5", "http://goo.gl/VYRM67")) + .build(); + String json = + "{" + + "\"name\":\"Stegosaurus\"," + + "\"length_meters\":9.0," + + "\"mass_kilograms\":5000.0," + + "\"period\":\"JURASSIC\"," + + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]" + + "}"; assertThat(gson.toJson(value)).isEqualTo(json); - com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); + com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = + gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); assertThat(decoded).isEqualTo(value); assertThat(decoded.hashCode()).isEqualTo(value.hashCode()); assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void interopListsOnly() { + @Test + public void interopListsOnly() { com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur value = new com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.Builder().build(); - String json = "{" - + "\"picture_urls\":[]" - + "}"; + String json = "{" + "\"picture_urls\":[]" + "}"; assertThat(gson.toJson(value)).isEqualTo(json); - com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); + com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = + gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); assertThat(decoded).isEqualTo(value); assertThat(decoded.hashCode()).isEqualTo(value.hashCode()); assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void interopEmptyObject() { + @Test + public void interopEmptyObject() { com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur value = new com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.Builder().build(); String json = "{}"; assertThat(gson.toJson(value)).isEqualTo("{\"picture_urls\":[]}"); - com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); + com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur decoded = + gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.javainteropkotlin.Dinosaur.class); assertThat(decoded).isEqualTo(value); assertThat(decoded.hashCode()).isEqualTo(value.hashCode()); assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void kotlinFullObject() { + @Test + public void kotlinFullObject() { com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur value = new com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur( "Stegosaurus", @@ -139,15 +144,15 @@ public class GsonNoAdapterTest { 9.0, 5_000.0, com.squareup.wire.proto2.geology.kotlin.Period.JURASSIC, - ByteString.EMPTY - ); - String json = "{" - + "\"name\":\"Stegosaurus\"," - + "\"length_meters\":9.0," - + "\"mass_kilograms\":5000.0," - + "\"period\":\"JURASSIC\"," - + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]" - + "}"; + ByteString.EMPTY); + String json = + "{" + + "\"name\":\"Stegosaurus\"," + + "\"length_meters\":9.0," + + "\"mass_kilograms\":5000.0," + + "\"period\":\"JURASSIC\"," + + "\"picture_urls\":[\"http://goo.gl/LD5KY5\",\"http://goo.gl/VYRM67\"]" + + "}"; assertThat(gson.toJson(value)).isEqualTo(json); com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur decoded = gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur.class); @@ -156,13 +161,12 @@ public class GsonNoAdapterTest { assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void kotlinListsOnly() { + @Test + public void kotlinListsOnly() { com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur value = - new com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur(null, Collections.emptyList(), null, - null, null, ByteString.EMPTY); - String json = "{" - + "\"picture_urls\":[]" - + "}"; + new com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur( + null, Collections.emptyList(), null, null, null, ByteString.EMPTY); + String json = "{" + "\"picture_urls\":[]" + "}"; assertThat(gson.toJson(value)).isEqualTo(json); com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur decoded = gson.fromJson(json, com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur.class); @@ -171,10 +175,11 @@ public class GsonNoAdapterTest { assertThat(decoded.toString()).isEqualTo(value.toString()); } - @Test public void kotlinEmptyObject() { + @Test + public void kotlinEmptyObject() { com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur value = - new com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur(null, Collections.emptyList(), null, - null, null, ByteString.EMPTY); + new com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur( + null, Collections.emptyList(), null, null, null, ByteString.EMPTY); String json = "{}"; assertThat(gson.toJson(value)).isEqualTo("{\"picture_urls\":[]}"); com.squareup.wire.proto2.dinosaurs.kotlin.Dinosaur decoded = diff --git a/wire-gson-support/src/test/java/com/squareup/wire/GsonTest.java b/wire-gson-support/src/test/java/com/squareup/wire/GsonTest.java index 57965cfcfb..06ad01189f 100644 --- a/wire-gson-support/src/test/java/com/squareup/wire/GsonTest.java +++ b/wire-gson-support/src/test/java/com/squareup/wire/GsonTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2013 Square Inc. + * Copyright (C) 2013 Square, Inc. * * 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 + * https://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, @@ -15,6 +15,9 @@ */ package com.squareup.wire; +import static com.squareup.wire.json.JsonUtils.assertJsonEquals; +import static org.assertj.core.api.Assertions.assertThat; + import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -34,9 +37,6 @@ import squareup.proto2.keywords.KeywordKotlin; import squareup.proto2.keywords.KeywordKotlin.KeywordKotlinEnum; -import static com.squareup.wire.json.JsonUtils.assertJsonEquals; -import static org.assertj.core.api.Assertions.assertThat; - public class GsonTest { private static final String ALL_TYPES_JSON; @@ -44,51 +44,55 @@ public class GsonTest { try { ALL_TYPES_JSON = Okio.buffer( - Okio.source( - new File("../wire-tests/src/commonTest/shared/json", "all_types_proto2.json")) - ).readUtf8(); + Okio.source( + new File( + "../wire-tests/src/commonTest/shared/json", "all_types_proto2.json"))) + .readUtf8(); } catch (IOException e) { throw new RuntimeException(e); } } - private final Gson gson = new GsonBuilder() - .registerTypeAdapterFactory(new WireTypeAdapterFactory()) - .disableHtmlEscaping() - .create(); + private final Gson gson = + new GsonBuilder() + .registerTypeAdapterFactory(new WireTypeAdapterFactory()) + .disableHtmlEscaping() + .create(); - @Test public void deserializationOfNullValues() { + @Test + public void deserializationOfNullValues() { // Modifying JSON string manually, cause serialization omits fields with null values. String json = ALL_TYPES_JSON.replace("\"opt_string\": \"124\",", "\"opt_string\": null,"); AllTypes deserializedAllTypesWithNulls = gson.fromJson(json, AllTypes.class); assertThat(deserializedAllTypesWithNulls.opt_string).isNull(); } - @Test public void nullRepeatedField() { + @Test + public void nullRepeatedField() { RepeatedPackedAndMap parsed = - gson.fromJson("{rep_int32=null,pack_int32=null,map_int32_int32=null}", - RepeatedPackedAndMap.class); + gson.fromJson( + "{rep_int32=null,pack_int32=null,map_int32_int32=null}", RepeatedPackedAndMap.class); assertThat(parsed.rep_int32).isEmpty(); assertThat(parsed.pack_int32).isEmpty(); assertThat(parsed.map_int32_int32).isEmpty(); } - @Test public void usedKeywordsInKotlin() { - KeywordKotlin keyword = new KeywordKotlin.Builder() - .object_("object") - .when_(1) - .enums( - Arrays.asList( - KeywordKotlinEnum.object_, - KeywordKotlinEnum.when_, - KeywordKotlinEnum.fun_, - KeywordKotlinEnum.return_, - KeywordKotlinEnum.open_, - KeywordKotlinEnum.name_, - KeywordKotlinEnum.ordinal_ - ) - ) - .build(); + @Test + public void usedKeywordsInKotlin() { + KeywordKotlin keyword = + new KeywordKotlin.Builder() + .object_("object") + .when_(1) + .enums( + Arrays.asList( + KeywordKotlinEnum.object_, + KeywordKotlinEnum.when_, + KeywordKotlinEnum.fun_, + KeywordKotlinEnum.return_, + KeywordKotlinEnum.open_, + KeywordKotlinEnum.name_, + KeywordKotlinEnum.ordinal_)) + .build(); String json = gson.toJson(keyword); assertJsonEquals( "{\"object\":\"object\",\"when\":1, \"fun\":{}, \"return\":[], \"enums\":[\"object\", " @@ -97,25 +101,26 @@ public class GsonTest { KeywordKotlin parseKeyword = gson.fromJson(json, KeywordKotlin.class); assertThat(parseKeyword).isEqualTo(keyword); - String generatedNamedJson = "{\"object_\":\"object\",\"when_\":1, \"fun_\":{}, \"return_\":[], " - + "\"enums\":[\"object_\", \"when_\", \"fun_\", \"return_\", \"open_\", \"name_\", " - + "\"ordinal_\"]}"; + String generatedNamedJson = + "{\"object_\":\"object\",\"when_\":1, \"fun_\":{}, \"return_\":[], " + + "\"enums\":[\"object_\", \"when_\", \"fun_\", \"return_\", \"open_\", \"name_\", " + + "\"ordinal_\"]}"; assertThat(gson.fromJson(generatedNamedJson, KeywordKotlin.class)).isEqualTo(keyword); } - @Test public void usedKeywordsInJava() { - KeywordJava keyword = new KeywordJava.Builder() - .final_("final") - .public_(true) - .enums( - Arrays.asList( - KeywordJavaEnum.final_, - KeywordJavaEnum.public_, - KeywordJavaEnum.package_, - KeywordJavaEnum.return_ - ) - ) - .build(); + @Test + public void usedKeywordsInJava() { + KeywordJava keyword = + new KeywordJava.Builder() + .final_("final") + .public_(true) + .enums( + Arrays.asList( + KeywordJavaEnum.final_, + KeywordJavaEnum.public_, + KeywordJavaEnum.package_, + KeywordJavaEnum.return_)) + .build(); String json = gson.toJson(keyword); assertJsonEquals( "{\"final\":\"final\", \"public\":true, \"package\":{}, \"return\":[], " @@ -124,12 +129,14 @@ public class GsonTest { KeywordJava parseKeyword = gson.fromJson(json, KeywordJava.class); assertThat(parseKeyword).isEqualTo(keyword); - String generatedNamedJson = "{\"final_\":\"final\", \"public_\":true, \"package_\":{}, " - + "\"return_\":[], \"enums\":[\"final_\", \"public_\", \"package_\", \"return_\"]}"; + String generatedNamedJson = + "{\"final_\":\"final\", \"public_\":true, \"package_\":{}, " + + "\"return_\":[], \"enums\":[\"final_\", \"public_\", \"package_\", \"return_\"]}"; assertThat(gson.fromJson(generatedNamedJson, KeywordJava.class)).isEqualTo(keyword); } - @Test public void enumKeywordsAtRootInKotlin() { + @Test + public void enumKeywordsAtRootInKotlin() { KeywordKotlinEnum constant = KeywordKotlinEnum.object_; String json = gson.toJson(constant); assertJsonEquals("\"object\"", json); @@ -140,7 +147,8 @@ public class GsonTest { assertThat(gson.fromJson(generatedNamedJson, KeywordKotlinEnum.class)).isEqualTo(constant); } - @Test public void enumKeywordsAtRootInJava() { + @Test + public void enumKeywordsAtRootInJava() { KeywordJavaEnum constant = KeywordJavaEnum.final_; String json = gson.toJson(constant); assertJsonEquals("\"final\"", json); @@ -151,62 +159,72 @@ public class GsonTest { assertThat(gson.fromJson(generatedNamedJson, KeywordJavaEnum.class)).isEqualTo(constant); } - @Test public void kotlinWithoutBuilderFromJson() { - Person person = gson.fromJson( - "{" - + "\"id\":1," - + "\"name\":\"Jo\"," - + "\"email\":\"foo@square.com\"," - + "\"phone\":[{\"number\": \"555-555-5555\"}, {\"number\": \"444-444-4444\"}]," - + "\"favorite_numbers\":[1, 2, 3]," - + "\"area_numbers\":{\"519\":\"555-5555\"}," - + "\"is_canadian\":true" - + "}", - Person.class); - assertThat(person).isEqualTo( - new Person( - "Jo", - 1, - "foo@square.com", - Arrays.asList(new PhoneNumber("555-555-5555", null, ByteString.EMPTY), new PhoneNumber("444-444-4444", null, ByteString.EMPTY)), - Arrays.asList(1, 2, 3), - ImmutableMap.builder().put(519, "555-5555").build(), - true, - ByteString.EMPTY)); + @Test + public void kotlinWithoutBuilderFromJson() { + Person person = + gson.fromJson( + "{" + + "\"id\":1," + + "\"name\":\"Jo\"," + + "\"email\":\"foo@square.com\"," + + "\"phone\":[{\"number\": \"555-555-5555\"}, {\"number\": \"444-444-4444\"}]," + + "\"favorite_numbers\":[1, 2, 3]," + + "\"area_numbers\":{\"519\":\"555-5555\"}," + + "\"is_canadian\":true" + + "}", + Person.class); + assertThat(person) + .isEqualTo( + new Person( + "Jo", + 1, + "foo@square.com", + Arrays.asList( + new PhoneNumber("555-555-5555", null, ByteString.EMPTY), + new PhoneNumber("444-444-4444", null, ByteString.EMPTY)), + Arrays.asList(1, 2, 3), + ImmutableMap.builder().put(519, "555-5555").build(), + true, + ByteString.EMPTY)); } - @Test public void kotlinWithoutBuilderToJson() { + @Test + public void kotlinWithoutBuilderToJson() { Person person = new Person( - "Jo", - 1, - "foo@square.com", - Arrays.asList(new PhoneNumber("555-555-5555", null, ByteString.EMPTY), new PhoneNumber("444-444-4444", null, ByteString.EMPTY)), - Arrays.asList(1, 2, 3), - ImmutableMap.builder().put(519, "555-5555").build(), - false, - ByteString.EMPTY); + "Jo", + 1, + "foo@square.com", + Arrays.asList( + new PhoneNumber("555-555-5555", null, ByteString.EMPTY), + new PhoneNumber("444-444-4444", null, ByteString.EMPTY)), + Arrays.asList(1, 2, 3), + ImmutableMap.builder().put(519, "555-5555").build(), + false, + ByteString.EMPTY); String json = gson.toJson(person); assertJsonEquals( - "{" - + "\"id\":1," - + "\"name\":\"Jo\"," - + "\"email\":\"foo@square.com\"," - + "\"phone\":[{\"number\": \"555-555-5555\"}, {\"number\": \"444-444-4444\"}]," - + "\"favorite_numbers\":[1, 2, 3]," - + "\"area_numbers\":{\"519\":\"555-5555\"}," - + "\"is_canadian\":false" - + "}", + "{" + + "\"id\":1," + + "\"name\":\"Jo\"," + + "\"email\":\"foo@square.com\"," + + "\"phone\":[{\"number\": \"555-555-5555\"}, {\"number\": \"444-444-4444\"}]," + + "\"favorite_numbers\":[1, 2, 3]," + + "\"area_numbers\":{\"519\":\"555-5555\"}," + + "\"is_canadian\":false" + + "}", json); } - @Test public void kotlinGettersFromJson() { - Getters getters = gson - .fromJson("{\"isa\":1,\"isA\":2,\"is_a\":3,\"is32\":32,\"isb\":true}", Getters.class); + @Test + public void kotlinGettersFromJson() { + Getters getters = + gson.fromJson("{\"isa\":1,\"isA\":2,\"is_a\":3,\"is32\":32,\"isb\":true}", Getters.class); assertThat(getters).isEqualTo(new Getters(1, 2, 3, 32, true, ByteString.EMPTY)); } - @Test public void kotlinGettersToJson() { + @Test + public void kotlinGettersToJson() { Getters getters = new Getters(1, 2, 3, 32, true, ByteString.EMPTY); String json = gson.toJson(getters); assertJsonEquals("{\"isa\":1,\"isA\":2,\"is_a\":3,\"is32\":32,\"isb\":true}", json); diff --git a/wire-java-generator/src/main/java/com/squareup/wire/java/JavaGenerator.java b/wire-java-generator/src/main/java/com/squareup/wire/java/JavaGenerator.java index 9c68cfa5d5..66870453fa 100644 --- a/wire-java-generator/src/main/java/com/squareup/wire/java/JavaGenerator.java +++ b/wire-java-generator/src/main/java/com/squareup/wire/java/JavaGenerator.java @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,6 +15,23 @@ */ package com.squareup.wire.java; +import static com.google.common.base.Preconditions.checkArgument; +import static com.squareup.wire.schema.internal.JvmLanguages.annotationName; +import static com.squareup.wire.schema.internal.JvmLanguages.annotationTargetType; +import static com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString; +import static com.squareup.wire.schema.internal.JvmLanguages.eligibleAsAnnotationMember; +import static com.squareup.wire.schema.internal.JvmLanguages.hasEponymousType; +import static com.squareup.wire.schema.internal.JvmLanguages.javaPackage; +import static com.squareup.wire.schema.internal.JvmLanguages.legacyQualifiedFieldName; +import static com.squareup.wire.schema.internal.JvmLanguages.optionValueToInt; +import static com.squareup.wire.schema.internal.JvmLanguages.optionValueToLong; +import static javax.lang.model.element.Modifier.ABSTRACT; +import static javax.lang.model.element.Modifier.FINAL; +import static javax.lang.model.element.Modifier.PRIVATE; +import static javax.lang.model.element.Modifier.PROTECTED; +import static javax.lang.model.element.Modifier.PUBLIC; +import static javax.lang.model.element.Modifier.STATIC; + import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.cache.CacheBuilder; @@ -84,23 +101,6 @@ import javax.annotation.Nullable; import okio.ByteString; -import static com.google.common.base.Preconditions.checkArgument; -import static com.squareup.wire.schema.internal.JvmLanguages.annotationName; -import static com.squareup.wire.schema.internal.JvmLanguages.annotationTargetType; -import static com.squareup.wire.schema.internal.JvmLanguages.builtInAdapterString; -import static com.squareup.wire.schema.internal.JvmLanguages.eligibleAsAnnotationMember; -import static com.squareup.wire.schema.internal.JvmLanguages.hasEponymousType; -import static com.squareup.wire.schema.internal.JvmLanguages.javaPackage; -import static com.squareup.wire.schema.internal.JvmLanguages.legacyQualifiedFieldName; -import static com.squareup.wire.schema.internal.JvmLanguages.optionValueToInt; -import static com.squareup.wire.schema.internal.JvmLanguages.optionValueToLong; -import static javax.lang.model.element.Modifier.ABSTRACT; -import static javax.lang.model.element.Modifier.FINAL; -import static javax.lang.model.element.Modifier.PRIVATE; -import static javax.lang.model.element.Modifier.PROTECTED; -import static javax.lang.model.element.Modifier.PUBLIC; -import static javax.lang.model.element.Modifier.STATIC; - /** * Generates Java source code that matches proto definitions. * @@ -120,11 +120,14 @@ public final class JavaGenerator { static final ClassName NULLABLE = ClassName.get("androidx.annotation", "Nullable"); static final ClassName CREATOR = ClassName.get("android.os", "Parcelable", "Creator"); - private static final Ordering TAG_ORDERING = Ordering.from(new Comparator() { - @Override public int compare(Field o1, Field o2) { - return Integer.compare(o1.getTag(), o2.getTag()); - } - }); + private static final Ordering TAG_ORDERING = + Ordering.from( + new Comparator() { + @Override + public int compare(Field o1, Field o2) { + return Integer.compare(o1.getTag(), o2.getTag()); + } + }); public static boolean builtInType(ProtoType protoType) { return BUILT_IN_TYPES_MAP.containsKey(protoType); @@ -151,14 +154,18 @@ public static boolean builtInType(ProtoType protoType) { .put(ProtoType.DURATION, ClassName.get("java.time", "Duration")) .put(ProtoType.TIMESTAMP, ClassName.get("java.time", "Instant")) .put(ProtoType.EMPTY, ClassName.get("kotlin", "Unit")) - .put(ProtoType.STRUCT_MAP, ParameterizedTypeName.get( - ClassName.get("java.util", "Map"), - ClassName.get("java.lang", "String"), WildcardTypeName.subtypeOf(Object.class))) + .put( + ProtoType.STRUCT_MAP, + ParameterizedTypeName.get( + ClassName.get("java.util", "Map"), + ClassName.get("java.lang", "String"), + WildcardTypeName.subtypeOf(Object.class))) .put(ProtoType.STRUCT_VALUE, ClassName.get("java.lang", "Object")) .put(ProtoType.STRUCT_NULL, ClassName.get("java.lang", "Void")) - .put(ProtoType.STRUCT_LIST, ParameterizedTypeName.get( - ClassName.get("java.util", "List"), - WildcardTypeName.subtypeOf(Object.class))) + .put( + ProtoType.STRUCT_LIST, + ParameterizedTypeName.get( + ClassName.get("java.util", "List"), WildcardTypeName.subtypeOf(Object.class))) .put(ProtoType.DOUBLE_VALUE, TypeName.DOUBLE) .put(ProtoType.FLOAT_VALUE, TypeName.FLOAT) .put(ProtoType.INT64_VALUE, TypeName.LONG) @@ -202,45 +209,50 @@ public static boolean builtInType(ProtoType protoType) { *

Name allocations are computed once and reused because some types may be needed when * generating other types. */ - private final LoadingCache nameAllocators - = CacheBuilder.newBuilder().build(new CacheLoader() { - @Override public NameAllocator load(Type type) throws Exception { - NameAllocator nameAllocator = new NameAllocator(); - - if (type instanceof MessageType) { - nameAllocator.newName("serialVersionUID", "serialVersionUID"); - nameAllocator.newName("ADAPTER", "ADAPTER"); - nameAllocator.newName("MESSAGE_OPTIONS", "MESSAGE_OPTIONS"); - if (emitAndroid) { - nameAllocator.newName("CREATOR", "CREATOR"); - } - - List fieldsAndOneOfFields = ((MessageType) type).getFieldsAndOneOfFields(); - Set collidingNames = collidingFieldNames(fieldsAndOneOfFields); - for (Field field : fieldsAndOneOfFields) { - String suggestion = collidingNames.contains(field.getName()) - || (field.getName().equals(field.getType().getSimpleName()) - && !field.getType().isScalar()) - || hasEponymousType(schema, field) - ? legacyQualifiedFieldName(field) - : field.getName(); - nameAllocator.newName(suggestion, field); - } - - } else if (type instanceof EnumType) { - nameAllocator.newName("value", "value"); - nameAllocator.newName("i", "i"); - nameAllocator.newName("reader", "reader"); - nameAllocator.newName("writer", "writer"); - - for (EnumConstant constant : ((EnumType) type).getConstants()) { - nameAllocator.newName(constant.getName(), constant); - } - } - - return nameAllocator; - } - }); + private final LoadingCache nameAllocators = + CacheBuilder.newBuilder() + .build( + new CacheLoader() { + @Override + public NameAllocator load(Type type) throws Exception { + NameAllocator nameAllocator = new NameAllocator(); + + if (type instanceof MessageType) { + nameAllocator.newName("serialVersionUID", "serialVersionUID"); + nameAllocator.newName("ADAPTER", "ADAPTER"); + nameAllocator.newName("MESSAGE_OPTIONS", "MESSAGE_OPTIONS"); + if (emitAndroid) { + nameAllocator.newName("CREATOR", "CREATOR"); + } + + List fieldsAndOneOfFields = + ((MessageType) type).getFieldsAndOneOfFields(); + Set collidingNames = collidingFieldNames(fieldsAndOneOfFields); + for (Field field : fieldsAndOneOfFields) { + String suggestion = + collidingNames.contains(field.getName()) + || (field.getName().equals(field.getType().getSimpleName()) + && !field.getType().isScalar()) + || hasEponymousType(schema, field) + ? legacyQualifiedFieldName(field) + : field.getName(); + nameAllocator.newName(suggestion, field); + } + + } else if (type instanceof EnumType) { + nameAllocator.newName("value", "value"); + nameAllocator.newName("i", "i"); + nameAllocator.newName("reader", "reader"); + nameAllocator.newName("writer", "writer"); + + for (EnumConstant constant : ((EnumType) type).getConstants()) { + nameAllocator.newName(constant.getName(), constant); + } + } + + return nameAllocator; + } + }); private final Schema schema; @@ -258,10 +270,17 @@ public static boolean builtInType(ProtoType protoType) { private final boolean emitAppliedOptions; private final boolean buildersOnly; - private JavaGenerator(Schema schema, Map typeToJavaName, - Map memberToJavaName, Profile profile, boolean emitAndroid, - boolean emitAndroidAnnotations, boolean emitCompact, boolean emitDeclaredOptions, - boolean emitAppliedOptions, boolean buildersOnly) { + private JavaGenerator( + Schema schema, + Map typeToJavaName, + Map memberToJavaName, + Profile profile, + boolean emitAndroid, + boolean emitAndroidAnnotations, + boolean emitCompact, + boolean emitDeclaredOptions, + boolean emitAppliedOptions, + boolean buildersOnly) { this.schema = schema; this.typeToJavaName = ImmutableMap.copyOf(typeToJavaName); this.memberToJavaName = ImmutableMap.copyOf(memberToJavaName); @@ -275,33 +294,87 @@ private JavaGenerator(Schema schema, Map typeToJavaName, } public JavaGenerator withAndroid(boolean emitAndroid) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public JavaGenerator withAndroidAnnotations(boolean emitAndroidAnnotations) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public JavaGenerator withCompact(boolean emitCompact) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public JavaGenerator withProfile(Profile profile) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public JavaGenerator withOptions(boolean emitDeclaredOptions, boolean emitAppliedOptions) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public JavaGenerator withBuildersOnly(boolean buildersOnly) { - return new JavaGenerator(schema, typeToJavaName, memberToJavaName, profile, emitAndroid, - emitAndroidAnnotations, emitCompact, emitDeclaredOptions, emitAppliedOptions, buildersOnly); + return new JavaGenerator( + schema, + typeToJavaName, + memberToJavaName, + profile, + emitAndroid, + emitAndroidAnnotations, + emitCompact, + emitDeclaredOptions, + emitAppliedOptions, + buildersOnly); } public static JavaGenerator get(Schema schema) { @@ -317,20 +390,31 @@ public static JavaGenerator get(Schema schema) { nameToJavaName.put(service.type(), className); } - putAllExtensions(schema, protoFile, - protoFile.getTypes(), protoFile.getExtendList(), - memberToJavaName); + putAllExtensions( + schema, protoFile, protoFile.getTypes(), protoFile.getExtendList(), memberToJavaName); } nameToJavaName.putAll(BUILT_IN_TYPES_MAP); - return new JavaGenerator(schema, nameToJavaName, memberToJavaName, new Profile(), - false /* emitAndroid */, false /* emitAndroidAnnotations */, false /* emitCompact */, - false /* emitDeclaredOptions */, false /* emitAppliedOptions */, false /* buildersOnly */); - } - - private static void putAllExtensions(Schema schema, ProtoFile protoFile, List types, - List extendList, Map memberToJavaName) { + return new JavaGenerator( + schema, + nameToJavaName, + memberToJavaName, + new Profile(), + false /* emitAndroid */, + false /* emitAndroidAnnotations */, + false /* emitCompact */, + false /* emitDeclaredOptions */, + false /* emitAppliedOptions */, + false /* buildersOnly */); + } + + private static void putAllExtensions( + Schema schema, + ProtoFile protoFile, + List types, + List extendList, + Map memberToJavaName) { for (Extend extend : extendList) { if (annotationTargetType(extend) == null) continue; @@ -344,9 +428,8 @@ private static void putAllExtensions(Schema schema, ProtoFile protoFile, List wireToJava, String javaPackage, - ClassName enclosingClassName, List types) { + private static void putAll( + Map wireToJava, + String javaPackage, + ClassName enclosingClassName, + List types) { for (Type type : types) { - ClassName className = enclosingClassName != null - ? enclosingClassName.nestedClass(type.getType().getSimpleName()) - : ClassName.get(javaPackage, type.getType().getSimpleName()); + ClassName className = + enclosingClassName != null + ? enclosingClassName.nestedClass(type.getType().getSimpleName()) + : ClassName.get(javaPackage, type.getType().getSimpleName()); wireToJava.put(type.getType(), className); putAll(wireToJava, javaPackage, className, type.getNestedTypes()); } @@ -520,17 +607,15 @@ static String sanitizeJavadoc(String documentation) { documentation = documentation.replaceAll("\\s+$", ""); documentation = documentation.replaceAll("\\*/", "*/"); // Rewrite '@see ' to use an html anchor tag - documentation = documentation.replaceAll( - "@see (http:" + URL_CHARS + "+)", "@see $1"); + documentation = + documentation.replaceAll("@see (http:" + URL_CHARS + "+)", "@see $1"); return documentation; } /** Returns the full name of the class generated for {@code type}. */ public ClassName generatedTypeName(Type type) { ClassName abstractAdapterName = abstractAdapterName(type.getType()); - return abstractAdapterName != null - ? abstractAdapterName - : (ClassName) typeName(type.getType()); + return abstractAdapterName != null ? abstractAdapterName : (ClassName) typeName(type.getType()); } /** Returns the generated code for {@code type}, which may be a top-level or a nested type. */ @@ -556,9 +641,10 @@ private TypeSpec generateEnum(EnumType type) { String value = nameAllocator.get("value"); ClassName javaType = (ClassName) typeName(type.getType()); - TypeSpec.Builder builder = TypeSpec.enumBuilder(javaType.simpleName()) - .addModifiers(PUBLIC) - .addSuperinterface(WireEnum.class); + TypeSpec.Builder builder = + TypeSpec.enumBuilder(javaType.simpleName()) + .addModifiers(PUBLIC) + .addSuperinterface(WireEnum.class); if (!type.getDocumentation().isEmpty()) { builder.addJavadoc("$L\n", sanitizeJavadoc(type.getDocumentation())); @@ -576,17 +662,19 @@ private TypeSpec generateEnum(EnumType type) { builder.addField(TypeName.INT, value, PRIVATE, FINAL); // Enum constructor takes the constant tag. - builder.addMethod(MethodSpec.constructorBuilder() - .addStatement("this.$1N = $1N", value) - .addParameter(TypeName.INT, value) - .build()); - - MethodSpec.Builder fromValueBuilder = MethodSpec.methodBuilder("fromValue") - .addJavadoc("Return the constant for {@code $N} or null.\n", value) - .addModifiers(PUBLIC, STATIC) - .returns(javaType) - .addParameter(int.class, value) - .beginControlFlow("switch ($N)", value); + builder.addMethod( + MethodSpec.constructorBuilder() + .addStatement("this.$1N = $1N", value) + .addParameter(TypeName.INT, value) + .build()); + + MethodSpec.Builder fromValueBuilder = + MethodSpec.methodBuilder("fromValue") + .addJavadoc("Return the constant for {@code $N} or null.\n", value) + .addModifiers(PUBLIC, STATIC) + .returns(javaType) + .addParameter(int.class, value) + .beginControlFlow("switch ($N)", value); Set seenTags = new LinkedHashSet<>(); for (EnumConstant constant : type.getConstants()) { @@ -612,18 +700,17 @@ private TypeSpec generateEnum(EnumType type) { // Ensure constant case tags are unique, which might not be the case if allow_alias is true. if (seenTags.add(constant.getTag())) { - fromValueBuilder.addStatement("case $L: return $L", constant.getTag(), - nameAllocator.get(constant)); + fromValueBuilder.addStatement( + "case $L: return $L", constant.getTag(), nameAllocator.get(constant)); } } - builder.addMethod(fromValueBuilder.addStatement("default: return null") - .endControlFlow() - .build()); + builder.addMethod( + fromValueBuilder.addStatement("default: return null").endControlFlow().build()); // ADAPTER - FieldSpec.Builder adapterBuilder = FieldSpec.builder(adapterOf(javaType), "ADAPTER") - .addModifiers(PUBLIC, STATIC, FINAL); + FieldSpec.Builder adapterBuilder = + FieldSpec.builder(adapterOf(javaType), "ADAPTER").addModifiers(PUBLIC, STATIC, FINAL); ClassName adapterJavaType = javaType.nestedClass("ProtoAdapter_" + javaType.simpleName()); if (!emitCompact) { adapterBuilder.initializer("new $T()", adapterJavaType); @@ -633,12 +720,13 @@ private TypeSpec generateEnum(EnumType type) { builder.addField(adapterBuilder.build()); // Public Getter - builder.addMethod(MethodSpec.methodBuilder("getValue") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(TypeName.INT) - .addStatement("return $N", value) - .build()); + builder.addMethod( + MethodSpec.methodBuilder("getValue") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(TypeName.INT) + .addStatement("return $N", value) + .build()); if (!emitCompact) { // Adds the ProtoAdapter implementation at the bottom. @@ -682,22 +770,25 @@ private TypeSpec generateMessage(MessageType type) { String protoAdapterName = "ProtoAdapter_" + javaType.simpleName(); String protoAdapterClassName = nameAllocator.newName(protoAdapterName); ClassName adapterJavaType = javaType.nestedClass(protoAdapterClassName); - builder.addField(messageAdapterField(adapterName, javaType, adapterJavaType, type.getType(), - type.getSyntax())); + builder.addField( + messageAdapterField( + adapterName, javaType, adapterJavaType, type.getType(), type.getSyntax())); // Note: The non-compact implementation is added at the very bottom of the surrounding type. if (emitAndroid) { TypeName creatorType = creatorOf(javaType); String creatorName = nameAllocator.get("CREATOR"); - builder.addField(FieldSpec.builder(creatorType, creatorName, PUBLIC, STATIC, FINAL) - .initializer("$T.newCreator($L)", ANDROID_MESSAGE, adapterName) - .build()); + builder.addField( + FieldSpec.builder(creatorType, creatorName, PUBLIC, STATIC, FINAL) + .initializer("$T.newCreator($L)", ANDROID_MESSAGE, adapterName) + .build()); } - builder.addField(FieldSpec.builder(TypeName.LONG, nameAllocator.get("serialVersionUID")) - .addModifiers(PRIVATE, STATIC, FINAL) - .initializer("$LL", 0L) - .build()); + builder.addField( + FieldSpec.builder(TypeName.LONG, nameAllocator.get("serialVersionUID")) + .addModifiers(PRIVATE, STATIC, FINAL) + .initializer("$LL", 0L) + .build()); for (Field field : type.getFieldsAndOneOfFields()) { TypeName fieldJavaType = fieldType(field); @@ -719,9 +810,7 @@ private TypeSpec generateMessage(MessageType type) { for (AnnotationSpec annotation : optionAnnotations(field.getOptions())) { fieldBuilder.addAnnotation(annotation); } - fieldBuilder.addAnnotation( - wireFieldAnnotation(nameAllocator, field, type) - ); + fieldBuilder.addAnnotation(wireFieldAnnotation(nameAllocator, field, type)); if (field.isExtension()) { fieldBuilder.addJavadoc("Extension source: $L\n", field.getLocation().withPathOnly()); } @@ -771,9 +860,7 @@ private TypeSpec generateMessage(MessageType type) { return builder.build(); } - /** - * Decides if a constructor should take all fields or a builder as a parameter. - */ + /** Decides if a constructor should take all fields or a builder as a parameter. */ private boolean constructorTakesAllFields(MessageType type) { return type.fields().size() < MAX_PARAMS_IN_CONSTRUCTOR; } @@ -781,8 +868,8 @@ private boolean constructorTakesAllFields(MessageType type) { private TypeSpec generateEnclosingType(EnclosingType type) { ClassName javaType = (ClassName) typeName(type.getType()); - TypeSpec.Builder builder = TypeSpec.classBuilder(javaType.simpleName()) - .addModifiers(PUBLIC, FINAL); + TypeSpec.Builder builder = + TypeSpec.classBuilder(javaType.simpleName()).addModifiers(PUBLIC, FINAL); if (javaType.enclosingClassName() != null) { builder.addModifiers(STATIC); } @@ -791,14 +878,16 @@ private TypeSpec generateEnclosingType(EnclosingType type) { if (!documentation.isEmpty()) { documentation += "\n\n

"; } - documentation += "NOTE: This type only exists to maintain class structure" - + " for its nested types and is not an actual message."; + documentation += + "NOTE: This type only exists to maintain class structure" + + " for its nested types and is not an actual message."; builder.addJavadoc("$L\n", documentation); - builder.addMethod(MethodSpec.constructorBuilder() - .addModifiers(PRIVATE) - .addStatement("throw new $T()", AssertionError.class) - .build()); + builder.addMethod( + MethodSpec.constructorBuilder() + .addModifiers(PRIVATE) + .addStatement("throw new $T()", AssertionError.class) + .build()); for (Type nestedType : type.getNestedTypes()) { builder.addType(generateType(nestedType)); @@ -815,8 +904,9 @@ public TypeSpec generateAdapterForCustomType(Type type) { TypeSpec.Builder adapter; if (type instanceof MessageType) { - adapter = messageAdapter(nameAllocator, (MessageType) type, typeName, adapterTypeName, null) - .toBuilder(); + adapter = + messageAdapter(nameAllocator, (MessageType) type, typeName, adapterTypeName, null) + .toBuilder(); } else { adapter = enumAdapter(nameAllocator, (EnumType) type, typeName, adapterTypeName).toBuilder(); } @@ -825,10 +915,12 @@ public TypeSpec generateAdapterForCustomType(Type type) { for (Type nestedType : type.getNestedTypes()) { if (profile.getAdapter(nestedType.getType()) == null) { - throw new IllegalArgumentException("Missing custom proto adapter for " - + nestedType.getType().getEnclosingTypeOrPackage() + "." - + nestedType.getType().getSimpleName() - + " when enclosing proto has custom proto adapter."); + throw new IllegalArgumentException( + "Missing custom proto adapter for " + + nestedType.getType().getEnclosingTypeOrPackage() + + "." + + nestedType.getType().getSimpleName() + + " when enclosing proto has custom proto adapter."); } adapter.addType(generateAdapterForCustomType(nestedType)); } @@ -848,13 +940,22 @@ private Set collidingFieldNames(List fields) { return collidingNames; } - private FieldSpec messageAdapterField(String adapterName, ClassName javaType, - ClassName adapterJavaType, ProtoType protoType, Syntax syntax) { - FieldSpec.Builder result = FieldSpec.builder(adapterOf(javaType), adapterName) - .addModifiers(PUBLIC, STATIC, FINAL); + private FieldSpec messageAdapterField( + String adapterName, + ClassName javaType, + ClassName adapterJavaType, + ProtoType protoType, + Syntax syntax) { + FieldSpec.Builder result = + FieldSpec.builder(adapterOf(javaType), adapterName).addModifiers(PUBLIC, STATIC, FINAL); if (emitCompact) { - result.initializer("$T.newMessageAdapter($T.class, $S, $T.$L)", - ProtoAdapter.class, javaType, protoType.getTypeUrl(), Syntax.class, syntax.name()); + result.initializer( + "$T.newMessageAdapter($T.class, $S, $T.$L)", + ProtoAdapter.class, + javaType, + protoType.getTypeUrl(), + Syntax.class, + syntax.name()); } else { result.initializer("new $T()", adapterJavaType); } @@ -863,17 +964,16 @@ private FieldSpec messageAdapterField(String adapterName, ClassName javaType, /** * Generates a custom enum adapter to decode a proto enum to a user-specified Java type. Users - * need to instantiate a constant instance of this adapter that provides all enum constants in - * the constructor in the proper order. - * - *

   {@code
+   * need to instantiate a constant instance of this adapter that provides all enum constants in the
+   * constructor in the proper order.
    *
-   *   public static final ProtoAdapter ADAPTER
-   *       = new RoshamboAdapter(Roshambo.ROCK, Roshambo.SCISSORS, Roshambo.PAPER);
+   * 
{@code
+   * public static final ProtoAdapter ADAPTER
+   *     = new RoshamboAdapter(Roshambo.ROCK, Roshambo.SCISSORS, Roshambo.PAPER);
    * }
*/ - private TypeSpec enumAdapter(NameAllocator nameAllocator, EnumType type, ClassName javaType, - ClassName adapterJavaType) { + private TypeSpec enumAdapter( + NameAllocator nameAllocator, EnumType type, ClassName javaType, ClassName adapterJavaType) { String value = nameAllocator.get("value"); String i = nameAllocator.get("i"); String reader = nameAllocator.get("reader"); @@ -885,12 +985,11 @@ private TypeSpec enumAdapter(NameAllocator nameAllocator, EnumType type, ClassNa MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); constructorBuilder.addModifiers(PUBLIC); - constructorBuilder.addStatement("super($T.VARINT, $T.class)", - FieldEncoding.class, javaType); + constructorBuilder.addStatement("super($T.VARINT, $T.class)", FieldEncoding.class, javaType); for (EnumConstant constant : type.getConstants()) { String name = nameAllocator.get(constant); - FieldSpec.Builder fieldBuilder = FieldSpec.builder(javaType, name) - .addModifiers(PROTECTED, FINAL); + FieldSpec.Builder fieldBuilder = + FieldSpec.builder(javaType, name).addModifiers(PROTECTED, FINAL); if (!constant.getDocumentation().isEmpty()) { fieldBuilder.addJavadoc("$L\n", sanitizeJavadoc(constant.getDocumentation())); } @@ -904,10 +1003,11 @@ private TypeSpec enumAdapter(NameAllocator nameAllocator, EnumType type, ClassNa } builder.addMethod(constructorBuilder.build()); - MethodSpec.Builder toValueBuilder = MethodSpec.methodBuilder("toValue") - .addModifiers(PROTECTED) - .returns(int.class) - .addParameter(javaType, value); + MethodSpec.Builder toValueBuilder = + MethodSpec.methodBuilder("toValue") + .addModifiers(PROTECTED) + .returns(int.class) + .addParameter(javaType, value); for (EnumConstant constant : type.getConstants()) { String name = nameAllocator.get(constant); toValueBuilder.addStatement("if ($N.equals($N)) return $L", value, name, constant.getTag()); @@ -915,48 +1015,55 @@ private TypeSpec enumAdapter(NameAllocator nameAllocator, EnumType type, ClassNa toValueBuilder.addStatement("return $L", -1); builder.addMethod(toValueBuilder.build()); - MethodSpec.Builder fromValueBuilder = MethodSpec.methodBuilder("fromValue") - .addModifiers(PROTECTED) - .returns(javaType) - .addParameter(int.class, value); + MethodSpec.Builder fromValueBuilder = + MethodSpec.methodBuilder("fromValue") + .addModifiers(PROTECTED) + .returns(javaType) + .addParameter(int.class, value); fromValueBuilder.beginControlFlow("switch ($N)", value); for (EnumConstant constant : type.getConstants()) { String name = nameAllocator.get(constant); fromValueBuilder.addStatement("case $L: return $N", constant.getTag(), name); } - fromValueBuilder.addStatement("default: throw new $T($N, $T.class)", - EnumConstantNotFoundException.class, value, javaType); + fromValueBuilder.addStatement( + "default: throw new $T($N, $T.class)", + EnumConstantNotFoundException.class, + value, + javaType); fromValueBuilder.endControlFlow(); builder.addMethod(fromValueBuilder.build()); - builder.addMethod(MethodSpec.methodBuilder("encodedSize") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(int.class) - .addParameter(javaType, value) - .addStatement("return $T.UINT32.encodedSize(toValue($N))", ProtoAdapter.class, value) - .build()); + builder.addMethod( + MethodSpec.methodBuilder("encodedSize") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(int.class) + .addParameter(javaType, value) + .addStatement("return $T.UINT32.encodedSize(toValue($N))", ProtoAdapter.class, value) + .build()); builder.addMethod(enumEncode(javaType, value, i, writer, false)); builder.addMethod(enumEncode(javaType, value, i, writer, true)); - builder.addMethod(MethodSpec.methodBuilder("decode") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(javaType) - .addParameter(ProtoReader.class, reader) - .addException(IOException.class) - .addStatement("int $N = $N.readVarint32()", value, reader) - .addStatement("return fromValue($N)", value) - .build()); + builder.addMethod( + MethodSpec.methodBuilder("decode") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(javaType) + .addParameter(ProtoReader.class, reader) + .addException(IOException.class) + .addStatement("int $N = $N.readVarint32()", value, reader) + .addStatement("return fromValue($N)", value) + .build()); - builder.addMethod(MethodSpec.methodBuilder("redact") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(javaType) - .addParameter(javaType, "value") - .addStatement("return value") - .build()); + builder.addMethod( + MethodSpec.methodBuilder("redact") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(javaType) + .addParameter(javaType, "value") + .addStatement("return value") + .build()); return builder.build(); } @@ -970,8 +1077,13 @@ private MethodSpec enumEncode( .addParameter(javaType, value) .addException(IOException.class) .addStatement("int $N = toValue($N)", localInt, value) - .addStatement("if ($N == $L) throw new $T($S + $N)", - localInt, -1, ProtocolException.class, "Unexpected enum constant: ", value) + .addStatement( + "if ($N == $L) throw new $T($S + $N)", + localInt, + -1, + ProtocolException.class, + "Unexpected enum constant: ", + value) .addStatement("$N.writeVarint32($N)", localWriter, localInt) .build(); } @@ -980,25 +1092,35 @@ private TypeSpec enumAdapter(ClassName javaType, ClassName adapterJavaType, Enum return TypeSpec.classBuilder(adapterJavaType.simpleName()) .superclass(enumAdapterOf(javaType)) .addModifiers(PRIVATE, STATIC, FINAL) - .addMethod(MethodSpec.constructorBuilder() - .addStatement("super($T.class, $T.$L, $L)", - javaType, Syntax.class, enumType.getSyntax().name(), identity(enumType)) - .build()) - .addMethod(MethodSpec.methodBuilder("fromValue") - .addAnnotation(Override.class) - .addModifiers(PROTECTED) - .returns(javaType) - .addParameter(int.class, "value") - .addStatement("return $T.fromValue(value)", javaType) - .build()) + .addMethod( + MethodSpec.constructorBuilder() + .addStatement( + "super($T.class, $T.$L, $L)", + javaType, + Syntax.class, + enumType.getSyntax().name(), + identity(enumType)) + .build()) + .addMethod( + MethodSpec.methodBuilder("fromValue") + .addAnnotation(Override.class) + .addModifiers(PROTECTED) + .returns(javaType) + .addParameter(int.class, "value") + .addStatement("return $T.fromValue(value)", javaType) + .build()) .build(); } - private TypeSpec messageAdapter(NameAllocator nameAllocator, MessageType type, ClassName javaType, - ClassName adapterJavaType, ClassName builderType) { + private TypeSpec messageAdapter( + NameAllocator nameAllocator, + MessageType type, + ClassName javaType, + ClassName adapterJavaType, + ClassName builderType) { boolean useBuilder = builderType != null; - TypeSpec.Builder adapter = TypeSpec.classBuilder(adapterJavaType.simpleName()) - .superclass(adapterOf(javaType)); + TypeSpec.Builder adapter = + TypeSpec.classBuilder(adapterJavaType.simpleName()).superclass(adapterOf(javaType)); if (useBuilder) { adapter.addModifiers(PRIVATE, STATIC, FINAL); @@ -1006,27 +1128,33 @@ private TypeSpec messageAdapter(NameAllocator nameAllocator, MessageType type, C adapter.addModifiers(PUBLIC, ABSTRACT); } - adapter.addMethod(MethodSpec.constructorBuilder() - .addModifiers(PUBLIC) - .addStatement("super($T.LENGTH_DELIMITED, $T.class, $S, $T.$L, null, $S)", - FieldEncoding.class, javaType, type.getType().getTypeUrl(), Syntax.class, - type.getSyntax().name(), type.getLocation().getPath()) - .build()); + adapter.addMethod( + MethodSpec.constructorBuilder() + .addModifiers(PUBLIC) + .addStatement( + "super($T.LENGTH_DELIMITED, $T.class, $S, $T.$L, null, $S)", + FieldEncoding.class, + javaType, + type.getType().getTypeUrl(), + Syntax.class, + type.getSyntax().name(), + type.getLocation().getPath()) + .build()); if (!useBuilder) { - MethodSpec.Builder fromProto = MethodSpec.methodBuilder("fromProto") - .addModifiers(PUBLIC, ABSTRACT) - .returns(javaType); + MethodSpec.Builder fromProto = + MethodSpec.methodBuilder("fromProto").addModifiers(PUBLIC, ABSTRACT).returns(javaType); for (Field field : type.getFieldsAndOneOfFields()) { TypeName fieldType = fieldType(field); String fieldName = nameAllocator.get(field); fromProto.addParameter(fieldType, fieldName); - adapter.addMethod(MethodSpec.methodBuilder(fieldName) - .addModifiers(PUBLIC, ABSTRACT) - .addParameter(javaType, "value") - .returns(fieldType) - .build()); + adapter.addMethod( + MethodSpec.methodBuilder(fieldName) + .addModifiers(PUBLIC, ABSTRACT) + .addParameter(javaType, "value") + .returns(fieldType) + .build()); } adapter.addMethod(fromProto.build()); @@ -1052,13 +1180,14 @@ private TypeSpec messageAdapter(NameAllocator nameAllocator, MessageType type, C return adapter.build(); } - private MethodSpec messageAdapterEncodedSize(NameAllocator nameAllocator, MessageType type, - TypeName javaType, boolean useBuilder) { - MethodSpec.Builder result = MethodSpec.methodBuilder("encodedSize") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(int.class) - .addParameter(javaType, "value"); + private MethodSpec messageAdapterEncodedSize( + NameAllocator nameAllocator, MessageType type, TypeName javaType, boolean useBuilder) { + MethodSpec.Builder result = + MethodSpec.methodBuilder("encodedSize") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(int.class) + .addParameter(javaType, "value"); String resultName = nameAllocator.clone().newName("result"); result.addStatement("int $L = 0", resultName); @@ -1068,10 +1197,14 @@ private MethodSpec messageAdapterEncodedSize(NameAllocator nameAllocator, Messag CodeBlock adapter = adapterFor(field, nameAllocator); boolean omitIdentity = field.getEncodeMode().equals(Field.EncodeMode.OMIT_IDENTITY); if (omitIdentity) { - result.beginControlFlow("if (!$T.equals(value.$L, $L))", ClassName.get(Objects.class), - fieldName, identityValue(field)); + result.beginControlFlow( + "if (!$T.equals(value.$L, $L))", + ClassName.get(Objects.class), + fieldName, + identityValue(field)); } - result.addCode("$L += ", resultName) + result + .addCode("$L += ", resultName) .addCode("$L.encodedSizeWithTag($L, ", adapter, fieldTag) .addCode((useBuilder ? "value.$L" : "$L(value)"), fieldName) .addCode(");\n"); @@ -1087,14 +1220,19 @@ private MethodSpec messageAdapterEncodedSize(NameAllocator nameAllocator, Messag return result.build(); } - private MethodSpec messageAdapterEncode(NameAllocator nameAllocator, MessageType type, - TypeName javaType, boolean useBuilder, boolean reverse) { - MethodSpec.Builder result = MethodSpec.methodBuilder("encode") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .addParameter(reverse ? ReverseProtoWriter.class : ProtoWriter.class, "writer") - .addParameter(javaType, "value") - .addException(IOException.class); + private MethodSpec messageAdapterEncode( + NameAllocator nameAllocator, + MessageType type, + TypeName javaType, + boolean useBuilder, + boolean reverse) { + MethodSpec.Builder result = + MethodSpec.methodBuilder("encode") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .addParameter(reverse ? ReverseProtoWriter.class : ProtoWriter.class, "writer") + .addParameter(javaType, "value") + .addException(IOException.class); List encodeCalls = new ArrayList<>(); @@ -1104,19 +1242,22 @@ private MethodSpec messageAdapterEncode(NameAllocator nameAllocator, MessageType String fieldName = nameAllocator.get(field); CodeBlock.Builder encodeCall = CodeBlock.builder(); if (field.getEncodeMode().equals(Field.EncodeMode.OMIT_IDENTITY)) { - encodeCall.add("if (!$T.equals(value.$L, $L)) ", ClassName.get(Objects.class), - fieldName, identityValue(field)); + encodeCall.add( + "if (!$T.equals(value.$L, $L)) ", + ClassName.get(Objects.class), + fieldName, + identityValue(field)); } - encodeCall.add("$L.encodeWithTag(writer, $L, ", adapter, fieldTag) + encodeCall + .add("$L.encodeWithTag(writer, $L, ", adapter, fieldTag) .add((useBuilder ? "value.$L" : "$L(value)"), fieldName) .add(");\n"); encodeCalls.add(encodeCall.build()); } if (useBuilder) { - encodeCalls.add(CodeBlock.builder() - .addStatement("writer.writeBytes(value.unknownFields())") - .build()); + encodeCalls.add( + CodeBlock.builder().addStatement("writer.writeBytes(value.unknownFields())").build()); } if (reverse) { @@ -1130,14 +1271,19 @@ private MethodSpec messageAdapterEncode(NameAllocator nameAllocator, MessageType return result.build(); } - private MethodSpec messageAdapterDecode(NameAllocator nameAllocator, MessageType type, - TypeName javaType, boolean useBuilder, ClassName builderJavaType) { - MethodSpec.Builder result = MethodSpec.methodBuilder("decode") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(javaType) - .addParameter(ProtoReader.class, "reader") - .addException(IOException.class); + private MethodSpec messageAdapterDecode( + NameAllocator nameAllocator, + MessageType type, + TypeName javaType, + boolean useBuilder, + ClassName builderJavaType) { + MethodSpec.Builder result = + MethodSpec.methodBuilder("decode") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(javaType) + .addParameter(ProtoReader.class, "reader") + .addException(IOException.class); List fields = TAG_ORDERING.sortedCopy(type.getFieldsAndOneOfFields()); @@ -1145,8 +1291,8 @@ private MethodSpec messageAdapterDecode(NameAllocator nameAllocator, MessageType result.addStatement("$1T builder = new $1T()", builderJavaType); } else { for (Field field : fields) { - result.addStatement("$T $N = $L", - fieldType(field), nameAllocator.get(field), initialValue(field)); + result.addStatement( + "$T $N = $L", fieldType(field), nameAllocator.get(field), initialValue(field)); } } @@ -1164,8 +1310,8 @@ private MethodSpec messageAdapterDecode(NameAllocator nameAllocator, MessageType result.addCode(";\n"); if (useBuilder) { result.nextControlFlow("catch ($T e)", EnumConstantNotFoundException.class); - result.addStatement("builder.addUnknownField(tag, $T.VARINT, (long) e.value)", - FieldEncoding.class); + result.addStatement( + "builder.addUnknownField(tag, $T.VARINT, (long) e.value)", FieldEncoding.class); result.endControlFlow(); // try/catch } else { result.nextControlFlow("catch ($T ignored)", EnumConstantNotFoundException.class); @@ -1174,8 +1320,8 @@ private MethodSpec messageAdapterDecode(NameAllocator nameAllocator, MessageType result.addStatement("break"); result.endControlFlow(); // case } else { - result.addCode("case $L: $L; break;\n", - fieldTag, decodeAndAssign(field, nameAllocator, useBuilder)); + result.addCode( + "case $L: $L; break;\n", fieldTag, decodeAndAssign(field, nameAllocator, useBuilder)); } } @@ -1217,8 +1363,8 @@ private CodeBlock decodeAndAssign(Field field, NameAllocator nameAllocator, bool if (field.isRepeated()) { return useBuilder ? field.getType().equals(ProtoType.STRUCT_NULL) - ? CodeBlock.of("builder.$L.add(($T) $L)", fieldName, Void.class, decode) - : CodeBlock.of("builder.$L.add($L)", fieldName, decode) + ? CodeBlock.of("builder.$L.add(($T) $L)", fieldName, Void.class, decode) + : CodeBlock.of("builder.$L.add($L)", fieldName, decode) : CodeBlock.of("$L.add($L)", fieldName, decode); } else if (field.getType().isMap()) { return useBuilder @@ -1227,19 +1373,24 @@ private CodeBlock decodeAndAssign(Field field, NameAllocator nameAllocator, bool } else { return useBuilder ? field.getType().equals(ProtoType.STRUCT_NULL) - ? CodeBlock.of("builder.$L(($T) $L)", fieldName, Void.class, decode) - : CodeBlock.of("builder.$L($L)", fieldName, decode) + ? CodeBlock.of("builder.$L(($T) $L)", fieldName, Void.class, decode) + : CodeBlock.of("builder.$L($L)", fieldName, decode) : CodeBlock.of("$L = $L", fieldName, decode); } } - private MethodSpec messageAdapterRedact(NameAllocator nameAllocator, MessageType type, - ClassName javaType, boolean useBuilder, ClassName builderJavaType) { - MethodSpec.Builder result = MethodSpec.methodBuilder("redact") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(javaType) - .addParameter(javaType, "value"); + private MethodSpec messageAdapterRedact( + NameAllocator nameAllocator, + MessageType type, + ClassName javaType, + boolean useBuilder, + ClassName builderJavaType) { + MethodSpec.Builder result = + MethodSpec.methodBuilder("redact") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(javaType) + .addParameter(javaType, "value"); int redactedFieldCount = 0; List requiredRedacted = new ArrayList<>(); @@ -1259,9 +1410,15 @@ private MethodSpec messageAdapterRedact(NameAllocator nameAllocator, MessageType if (!requiredRedacted.isEmpty()) { boolean isPlural = requiredRedacted.size() != 1; - result.addStatement("throw new $T($S)", UnsupportedOperationException.class, - (isPlural ? "Fields" : "Field") + " '" + Joiner.on("', '").join(requiredRedacted) + "' " - + (isPlural ? "are" : "is") + " required and cannot be redacted."); + result.addStatement( + "throw new $T($S)", + UnsupportedOperationException.class, + (isPlural ? "Fields" : "Field") + + " '" + + Joiner.on("', '").join(requiredRedacted) + + "' " + + (isPlural ? "are" : "is") + + " required and cannot be redacted."); return result.build(); } @@ -1280,15 +1437,15 @@ private MethodSpec messageAdapterRedact(NameAllocator nameAllocator, MessageType } else if (!field.getType().isScalar() && !isEnum(field.getType())) { if (field.isRepeated()) { CodeBlock adapter = singleAdapterFor(field, nameAllocator); - result.addStatement("$T.redactElements(builder.$N, $L)", Internal.class, fieldName, - adapter); + result.addStatement( + "$T.redactElements(builder.$N, $L)", Internal.class, fieldName, adapter); } else if (field.getType().isMap()) { // We only need to ask the values to redact themselves if the type is a message. if (!field.getType().getValueType().isScalar() && !isEnum(field.getType().getValueType())) { CodeBlock adapter = singleAdapterFor(field.getType().getValueType()); - result.addStatement("$T.redactElements(builder.$N, $L)", Internal.class, fieldName, - adapter); + result.addStatement( + "$T.redactElements(builder.$N, $L)", Internal.class, fieldName, adapter); } } else { CodeBlock adapter = adapterFor(field, nameAllocator); @@ -1315,7 +1472,8 @@ private String fieldName(ProtoType type, Field field) { private TypeName fieldType(Field field) { ProtoType type = field.getType(); if (type.isMap()) { - return ParameterizedTypeName.get(ClassName.get(Map.class), + return ParameterizedTypeName.get( + ClassName.get(Map.class), typeName(type.getKeyType()).box(), typeName(type.getValueType()).box()); } @@ -1352,8 +1510,8 @@ private FieldSpec defaultField(NameAllocator nameAllocator, Field field, TypeNam // type = INT32 // ) // - private AnnotationSpec wireFieldAnnotation(NameAllocator nameAllocator, Field field, - MessageType message) { + private AnnotationSpec wireFieldAnnotation( + NameAllocator nameAllocator, Field field, MessageType message) { AnnotationSpec.Builder result = AnnotationSpec.builder(WireField.class); NameAllocator localNameAllocator = nameAllocator.clone(); @@ -1378,7 +1536,7 @@ private AnnotationSpec wireFieldAnnotation(NameAllocator nameAllocator, Field fi if (field.getType().isWrapper()) { wireFieldLabel = null; } else { - wireFieldLabel = WireField.Label.OMIT_IDENTITY; + wireFieldLabel = WireField.Label.OMIT_IDENTITY; } break; case REPEATED: @@ -1432,8 +1590,8 @@ private AnnotationSpec wireFieldAnnotation(NameAllocator nameAllocator, Field fi // declaredName = "final", // ) // - private @Nullable AnnotationSpec wireEnumConstantAnnotation(NameAllocator nameAllocator, - EnumConstant constant) { + private @Nullable AnnotationSpec wireEnumConstantAnnotation( + NameAllocator nameAllocator, EnumConstant constant) { AnnotationSpec.Builder result = AnnotationSpec.builder(WireEnumConstant.class); NameAllocator localNameAllocator = nameAllocator.clone(); @@ -1515,8 +1673,7 @@ private MethodSpec messageFieldsConstructor(NameAllocator nameAllocator, Message // } // private MethodSpec messageConstructor( - NameAllocator nameAllocator, MessageType type, - ClassName builderJavaType) { + NameAllocator nameAllocator, MessageType type, ClassName builderJavaType) { boolean constructorTakesAllFields = constructorTakesAllFields(type); NameAllocator localNameAllocator = nameAllocator.clone(); @@ -1524,8 +1681,9 @@ private MethodSpec messageConstructor( String adapterName = localNameAllocator.get("ADAPTER"); String unknownFieldsName = localNameAllocator.newName("unknownFields"); String builderName = localNameAllocator.newName("builder"); - MethodSpec.Builder result = MethodSpec.constructorBuilder() - .addStatement("super($N, $N)", adapterName, unknownFieldsName); + MethodSpec.Builder result = + MethodSpec.constructorBuilder() + .addStatement("super($N, $N)", adapterName, unknownFieldsName); if (!buildersOnly) result.addModifiers(PUBLIC); for (OneOf oneOf : type.getOneOfs()) { @@ -1543,16 +1701,16 @@ private MethodSpec messageConstructor( } CodeBlock fieldNames = fieldNamesBuilder.build(); result.beginControlFlow("if ($T.countNonNull($L) > 1)", Internal.class, fieldNames); - result.addStatement("throw new IllegalArgumentException($S)", + result.addStatement( + "throw new IllegalArgumentException($S)", "at most one of " + fieldNames + " may be non-null"); result.endControlFlow(); } for (Field field : type.getFieldsAndOneOfFields()) { TypeName javaType = fieldType(field); String fieldName = localNameAllocator.get(field); - String fieldAccessName = constructorTakesAllFields - ? fieldName - : builderName + "." + fieldName; + String fieldAccessName = + constructorTakesAllFields ? fieldName : builderName + "." + fieldName; if (constructorTakesAllFields) { ParameterSpec.Builder param = ParameterSpec.builder(javaType, fieldName); @@ -1565,24 +1723,30 @@ private MethodSpec messageConstructor( if (field.getEncodeMode() == Field.EncodeMode.OMIT_IDENTITY) { // Other scalars use not-boxed types to guarantee a value. if (field.getType().isScalar() - && (field.getType() == ProtoType.STRING || field.getType() == ProtoType.BYTES) + && (field.getType() == ProtoType.STRING || field.getType() == ProtoType.BYTES) || (isEnum(field.getType()) && !field.getType().equals(ProtoType.STRUCT_NULL))) { result.beginControlFlow("if ($L == null)", fieldAccessName); - result.addStatement("throw new IllegalArgumentException($S)", - fieldAccessName + " == null"); + result.addStatement( + "throw new IllegalArgumentException($S)", fieldAccessName + " == null"); result.endControlFlow(); } } if (field.getType().isMap() && isStruct(field.getType().getValueType())) { - result.addStatement("this.$1L = $2T.immutableCopyOfMapWithStructValues($1S, $3L)", - fieldName, Internal.class, fieldAccessName); + result.addStatement( + "this.$1L = $2T.immutableCopyOfMapWithStructValues($1S, $3L)", + fieldName, + Internal.class, + fieldAccessName); } else if (isStruct(field.getType())) { - result.addStatement("this.$1L = $2T.immutableCopyOfStruct($1S, $3L)", fieldName, - Internal.class, fieldAccessName); + result.addStatement( + "this.$1L = $2T.immutableCopyOfStruct($1S, $3L)", + fieldName, + Internal.class, + fieldAccessName); } else if (field.isRepeated() || field.getType().isMap()) { - result.addStatement("this.$1L = $2T.immutableCopyOf($1S, $3L)", fieldName, - Internal.class, fieldAccessName); + result.addStatement( + "this.$1L = $2T.immutableCopyOf($1S, $3L)", fieldName, Internal.class, fieldAccessName); } else { result.addStatement("this.$1L = $2L", fieldName, fieldAccessName); } @@ -1632,11 +1796,12 @@ private MethodSpec messageEquals(NameAllocator nameAllocator, MessageType type) String oName = localNameAllocator.newName("o"); TypeName javaType = typeName(type.getType()); - MethodSpec.Builder result = MethodSpec.methodBuilder("equals") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(boolean.class) - .addParameter(Object.class, otherName); + MethodSpec.Builder result = + MethodSpec.methodBuilder("equals") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(boolean.class) + .addParameter(Object.class, otherName); result.addStatement("if ($N == this) return true", otherName); result.addStatement("if (!($N instanceof $T)) return false", otherName, javaType); @@ -1678,10 +1843,11 @@ private MethodSpec messageHashCode(NameAllocator nameAllocator, MessageType type NameAllocator localNameAllocator = nameAllocator.clone(); String resultName = localNameAllocator.newName("result"); - MethodSpec.Builder result = MethodSpec.methodBuilder("hashCode") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(int.class); + MethodSpec.Builder result = + MethodSpec.methodBuilder("hashCode") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(int.class); List fields = type.getFieldsAndOneOfFields(); if (fields.isEmpty()) { @@ -1706,9 +1872,7 @@ private MethodSpec messageHashCode(NameAllocator nameAllocator, MessageType type result.addStatement("$T.hashCode($N)", Float.class, fieldName); } else if (typeName == TypeName.DOUBLE) { result.addStatement("$T.hashCode($N)", Double.class, fieldName); - } else if (field.isRequired() - || field.isRepeated() - || field.getType().isMap()) { + } else if (field.isRequired() || field.isRepeated() || field.getType().isMap()) { result.addStatement("$L.hashCode()", fieldName); } else { result.addStatement("($1L != null ? $1L.hashCode() : 0)", fieldName); @@ -1731,19 +1895,22 @@ private MethodSpec messageHashCode(NameAllocator nameAllocator, MessageType type // return result; // } // - private MethodSpec mapAdapter(NameAllocator nameAllocator, TypeName adapterType, String fieldName, - ProtoType mapType) { + private MethodSpec mapAdapter( + NameAllocator nameAllocator, TypeName adapterType, String fieldName, ProtoType mapType) { NameAllocator localNameAllocator = nameAllocator.clone(); String resultName = localNameAllocator.newName("result"); - MethodSpec.Builder result = MethodSpec.methodBuilder(fieldName + "Adapter") - .addModifiers(PRIVATE) - .returns(adapterType); + MethodSpec.Builder result = + MethodSpec.methodBuilder(fieldName + "Adapter").addModifiers(PRIVATE).returns(adapterType); result.addStatement("$T $N = $N", adapterType, resultName, fieldName); result.beginControlFlow("if ($N == null)", resultName); - result.addStatement("$N = $T.newMapAdapter($L, $L)", resultName, ADAPTER, - singleAdapterFor(mapType.getKeyType()), singleAdapterFor(mapType.getValueType())); + result.addStatement( + "$N = $T.newMapAdapter($L, $L)", + resultName, + ADAPTER, + singleAdapterFor(mapType.getKeyType()), + singleAdapterFor(mapType.getValueType())); result.addStatement("$N = $N", fieldName, resultName); result.endControlFlow(); result.addStatement("return $N", resultName); @@ -1753,10 +1920,11 @@ private MethodSpec mapAdapter(NameAllocator nameAllocator, TypeName adapterType, private MethodSpec messageToString(NameAllocator nameAllocator, MessageType type) { NameAllocator localNameAllocator = nameAllocator.clone(); - MethodSpec.Builder result = MethodSpec.methodBuilder("toString") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(String.class); + MethodSpec.Builder result = + MethodSpec.methodBuilder("toString") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(String.class); String builderName = localNameAllocator.newName("builder"); result.addStatement("$1T $2N = new $1T()", StringBuilder.class, builderName); @@ -1770,27 +1938,31 @@ private MethodSpec messageToString(NameAllocator nameAllocator, MessageType type result.addCode("if ($N != null) ", fieldName); } if (field.isRedacted()) { - result.addStatement("$N.append(\", $N=$L\")", builderName, field.getName(), - DOUBLE_FULL_BLOCK); + result.addStatement( + "$N.append(\", $N=$L\")", builderName, field.getName(), DOUBLE_FULL_BLOCK); } else if (field.getType().equals(ProtoType.STRING)) { - result.addStatement("$N.append(\", $N=\").append($T.sanitize($L))", builderName, - field.getName(), Internal.class, fieldName); - } else { - result.addStatement("$N.append(\", $N=\").append($L)", builderName, field.getName(), + result.addStatement( + "$N.append(\", $N=\").append($T.sanitize($L))", + builderName, + field.getName(), + Internal.class, fieldName); + } else { + result.addStatement( + "$N.append(\", $N=\").append($L)", builderName, field.getName(), fieldName); } } - result.addStatement("return builder.replace(0, 2, \"$L{\").append('}').toString()", + result.addStatement( + "return builder.replace(0, 2, \"$L{\").append('}').toString()", type.getType().getSimpleName()); return result.build(); } - private TypeSpec builder(NameAllocator nameAllocator, MessageType type, ClassName javaType, - ClassName builderType) { - TypeSpec.Builder result = TypeSpec.classBuilder("Builder") - .addModifiers(PUBLIC, STATIC, FINAL); + private TypeSpec builder( + NameAllocator nameAllocator, MessageType type, ClassName javaType, ClassName builderType) { + TypeSpec.Builder result = TypeSpec.classBuilder("Builder").addModifiers(PUBLIC, STATIC, FINAL); result.superclass(builderOf(javaType, builderType)); @@ -1868,11 +2040,12 @@ private MethodSpec newBuilder(NameAllocator nameAllocator, MessageType message) ClassName javaType = (ClassName) typeName(message.getType()); ClassName builderJavaType = javaType.nestedClass("Builder"); - MethodSpec.Builder result = MethodSpec.methodBuilder("newBuilder") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(builderJavaType) - .addStatement("$1T $2L = new $1T()", builderJavaType, builderName); + MethodSpec.Builder result = + MethodSpec.methodBuilder("newBuilder") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(builderJavaType) + .addStatement("$1T $2L = new $1T()", builderJavaType, builderName); List fields = message.getFieldsAndOneOfFields(); for (Field field : fields) { @@ -1894,10 +2067,11 @@ private MethodSpec setter( TypeName javaType = fieldType(field); String fieldName = nameAllocator.get(field); - MethodSpec.Builder result = MethodSpec.methodBuilder(fieldName) - .addModifiers(PUBLIC) - .addParameter(javaType, fieldName) - .returns(builderType); + MethodSpec.Builder result = + MethodSpec.methodBuilder(fieldName) + .addModifiers(PUBLIC) + .addParameter(javaType, fieldName) + .returns(builderType); if (!field.getDocumentation().isEmpty()) { result.addJavadoc("$L\n", sanitizeJavadoc(field.getDocumentation())); @@ -1940,10 +2114,11 @@ private MethodSpec setter( // private MethodSpec builderBuild( NameAllocator nameAllocator, MessageType message, ClassName javaType) { - MethodSpec.Builder result = MethodSpec.methodBuilder("build") - .addAnnotation(Override.class) - .addModifiers(PUBLIC) - .returns(javaType); + MethodSpec.Builder result = + MethodSpec.methodBuilder("build") + .addAnnotation(Override.class) + .addModifiers(PUBLIC) + .returns(javaType); List requiredFields = message.getRequiredFields(); if (!requiredFields.isEmpty()) { @@ -1954,13 +2129,12 @@ private MethodSpec builderBuild( if (i > 0) conditionals.add("\n|| "); conditionals.add("$L == null", nameAllocator.get(requiredField)); if (i > 0) missingArgs.add(",\n"); - missingArgs.add("$1L, $2S", nameAllocator.get(requiredField), - requiredField.getName()); + missingArgs.add("$1L, $2S", nameAllocator.get(requiredField), requiredField.getName()); } - result.beginControlFlow("if ($L)", conditionals.add("$]").build()) - .addStatement("throw $T.missingRequiredFields($L)", Internal.class, - missingArgs.build()) + result + .beginControlFlow("if ($L)", conditionals.add("$]").build()) + .addStatement("throw $T.missingRequiredFields($L)", Internal.class, missingArgs.build()) .endControlFlow(); } @@ -2019,7 +2193,7 @@ private CodeBlock fieldInitializer(ProtoType type, @Nullable Object value, boole ProtoMember protoMember = (ProtoMember) entry.getKey(); Field field = schema.getField(protoMember); CodeBlock valueInitializer = - fieldInitializer(field.getType(), entry.getValue(), annotation); + fieldInitializer(field.getType(), entry.getValue(), annotation); builder.add("\n$>$>.$L($L)$<$<", fieldName(type, field), valueInitializer); } builder.add("\n$>$>.build()$<$<"); @@ -2067,7 +2241,9 @@ private CodeBlock fieldInitializer(ProtoType type, @Nullable Object value, boole if (value == null) { return CodeBlock.of("$T.EMPTY", ByteString.class); } else { - return CodeBlock.of("$T.decodeBase64($S)", ByteString.class, + return CodeBlock.of( + "$T.decodeBase64($S)", + ByteString.class, ByteString.encodeString(String.valueOf(value), Charsets.ISO_8859_1).base64()); } @@ -2117,7 +2293,9 @@ private CodeBlock identity(EnumType enumType) { EnumConstant constantZero = enumType.constant(0); if (constantZero == null) return CodeBlock.of("null"); - return CodeBlock.of("$T.$L", typeName(enumType.getType()), + return CodeBlock.of( + "$T.$L", + typeName(enumType.getType()), nameAllocators.getUnchecked(enumType).get(constantZero)); } @@ -2146,12 +2324,12 @@ public ClassName generatedTypeName(ProtoMember member) { if (field.getLabel().equals(Field.Label.REPEATED)) { TypeName typeName = typeName(field.getType()); if (typeName.equals(TypeName.LONG) - || typeName.equals(TypeName.INT) - || typeName.equals(TypeName.FLOAT) - || typeName.equals(TypeName.DOUBLE) - || typeName.equals(TypeName.BOOLEAN) - || typeName.equals(ClassName.get(String.class)) - || isEnum(field.getType())) { + || typeName.equals(TypeName.INT) + || typeName.equals(TypeName.FLOAT) + || typeName.equals(TypeName.DOUBLE) + || typeName.equals(TypeName.BOOLEAN) + || typeName.equals(ClassName.get(String.class)) + || isEnum(field.getType())) { returnType = ArrayTypeName.of(typeName); } else { throw new IllegalStateException("Unsupported annotation for " + field.getType()); @@ -2162,23 +2340,27 @@ public ClassName generatedTypeName(ProtoMember member) { ClassName javaType = generatedTypeName(extend.member(field)); - TypeSpec.Builder builder = TypeSpec.annotationBuilder(javaType.simpleName()) - .addModifiers(PUBLIC) - .addAnnotation(AnnotationSpec.builder(Retention.class) - .addMember("value", "$T.$L", RetentionPolicy.class, RetentionPolicy.RUNTIME) - .build()) - .addAnnotation(AnnotationSpec.builder(Target.class) - .addMember("value", "$T.$L", ElementType.class, elementType) - .build()); + TypeSpec.Builder builder = + TypeSpec.annotationBuilder(javaType.simpleName()) + .addModifiers(PUBLIC) + .addAnnotation( + AnnotationSpec.builder(Retention.class) + .addMember("value", "$T.$L", RetentionPolicy.class, RetentionPolicy.RUNTIME) + .build()) + .addAnnotation( + AnnotationSpec.builder(Target.class) + .addMember("value", "$T.$L", ElementType.class, elementType) + .build()); if (!field.getDocumentation().isEmpty()) { builder.addJavadoc("$L\n", field.getDocumentation()); } - builder.addMethod(MethodSpec.methodBuilder("value") - .returns(returnType) - .addModifiers(PUBLIC, ABSTRACT) - .build()); + builder.addMethod( + MethodSpec.methodBuilder("value") + .returns(returnType) + .addModifiers(PUBLIC, ABSTRACT) + .build()); return builder.build(); } @@ -2205,9 +2387,6 @@ private List optionAnnotations(Options options) { ClassName type = annotationName(protoFile, field, new ClassNameFactory()); CodeBlock fieldValue = fieldInitializer(field.getType(), value, true); - return AnnotationSpec.builder(type) - .addMember("value", fieldValue) - .build(); + return AnnotationSpec.builder(type).addMember("value", fieldValue).build(); } } - diff --git a/wire-java-generator/src/main/java/com/squareup/wire/java/JavaSchemaHandler.kt b/wire-java-generator/src/main/java/com/squareup/wire/java/JavaSchemaHandler.kt index fcd82420e0..1d537c1a6a 100644 --- a/wire-java-generator/src/main/java/com/squareup/wire/java/JavaSchemaHandler.kt +++ b/wire-java-generator/src/main/java/com/squareup/wire/java/JavaSchemaHandler.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.java import com.squareup.javapoet.JavaFile @@ -8,8 +23,8 @@ import com.squareup.wire.schema.Schema import com.squareup.wire.schema.SchemaHandler import com.squareup.wire.schema.Service import com.squareup.wire.schema.Type -import okio.Path import java.io.IOException +import okio.Path class JavaSchemaHandler( /** True for emitted types to implement `android.os.Parcelable`. */ @@ -87,7 +102,9 @@ class JavaSchemaHandler( "${javaTypeName.simpleName()}.java" context.logger.artifactHandled( - outDirectory, "${javaFile.packageName}.${javaFile.typeSpec.name}", "Java" + outDirectory, + "${javaFile.packageName}.${javaFile.typeSpec.name}", + "Java", ) try { context.fileSystem.createDirectories(filePath.parent!!) @@ -96,7 +113,8 @@ class JavaSchemaHandler( } } catch (e: IOException) { throw IOException( - "Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} to $outDirectory", e + "Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} to $outDirectory", + e, ) } return filePath diff --git a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt index 59781c58fd..9637f699e8 100644 --- a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt +++ b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt @@ -1,11 +1,11 @@ /* - * Copyright (C) 2022 Block, Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -48,7 +48,8 @@ internal class JavaGeneratorHelper(private val schema: Schema) { } @Throws(IOException::class) - @JvmOverloads fun generateJava(typeName: String, profileName: String? = null): String { + @JvmOverloads + fun generateJava(typeName: String, profileName: String? = null): String { val javaGenerator = JavaGenerator.get(schema) .withProfile(profile(profileName)) val type = schema.getType(typeName) diff --git a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorTest.java b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorTest.java index 5a2772f066..592127e10e 100644 --- a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorTest.java +++ b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorTest.java @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -15,6 +15,10 @@ */ package com.squareup.wire.java; +import static com.google.common.truth.Truth.assertThat; +import static com.squareup.wire.schema.SchemaHelpersKt.addFromTest; +import static org.junit.Assert.fail; + import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import com.squareup.wire.SchemaBuilder; @@ -25,382 +29,434 @@ import okio.Path; import org.junit.Test; -import static com.google.common.truth.Truth.assertThat; -import static com.squareup.wire.schema.SchemaHelpersKt.addFromTest; -import static org.junit.Assert.fail; - public final class JavaGeneratorTest { - @Test public void sanitizeJavadocStripsTrailingWhitespace() { + @Test + public void sanitizeJavadocStripsTrailingWhitespace() { String input = "The quick brown fox \nJumps over \n\t \t\nThe lazy dog "; String expected = "The quick brown fox\nJumps over\n\nThe lazy dog"; assertThat(JavaGenerator.sanitizeJavadoc(input)).isEqualTo(expected); } - @Test public void sanitizeJavadocWrapsSeeLinks() { + @Test + public void sanitizeJavadocWrapsSeeLinks() { String input = "Google query.\n\n@see http://google.com"; String expected = "Google query.\n\n@see http://google.com"; assertThat(JavaGenerator.sanitizeJavadoc(input)).isEqualTo(expected); } - @Test public void sanitizeJavadocStarSlash() { + @Test + public void sanitizeJavadocStarSlash() { String input = "/* comment inside comment. */"; String expected = "/* comment inside comment. */"; assertThat(JavaGenerator.sanitizeJavadoc(input)).isEqualTo(expected); } - @Test public void generateTypeUsesNameAllocatorInMessageBuilderBuild() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message Message {\n" - + " required float long = 1;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .generateJava("Message")).contains("" - + " @Override\n" - + " public Message build() {\n" - + " if (long_ == null) {\n" - + " throw Internal.missingRequiredFields(long_, \"long\");\n" - + " }\n" - + " return new Message(long_, super.buildUnknownFields());\n" - + " }\n"); + @Test + public void generateTypeUsesNameAllocatorInMessageBuilderBuild() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + "message Message {\n" + " required float long = 1;\n" + "}\n") + .build(); + assertThat(new JavaWithProfilesGenerator(schema).generateJava("Message")) + .contains( + "" + + " @Override\n" + + " public Message build() {\n" + + " if (long_ == null) {\n" + + " throw Internal.missingRequiredFields(long_, \"long\");\n" + + " }\n" + + " return new Message(long_, super.buildUnknownFields());\n" + + " }\n"); } - @Test public void tooManyFieldsTest() throws Exception { + @Test + public void tooManyFieldsTest() throws Exception { StringBuilder s = new StringBuilder(); for (int i = 1; i < 257; i++) { s.append(" repeated int32 field_" + i + " = " + i + ";\n"); } - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message Message {\n" - + s.toString() - + " oneof oneof_name {\n" - + " int32 foo = 257;\n" - + " int32 bar = 258;\n" - + " }\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .generateJava("Message")).contains("" - + "public Message(Builder builder, ByteString unknownFields)"); + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message Message {\n" + + s.toString() + + " oneof oneof_name {\n" + + " int32 foo = 257;\n" + + " int32 bar = 258;\n" + + " }\n" + + "}\n") + .build(); + assertThat(new JavaWithProfilesGenerator(schema).generateJava("Message")) + .contains("" + "public Message(Builder builder, ByteString unknownFields)"); } - @Test public void map() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message Message {\n" - + " map templates = 1;\n" - + " message CdnResource {\n" - + " }\n" - + "}\n") - .build(); + @Test + public void map() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message Message {\n" + + " map templates = 1;\n" + + " message CdnResource {\n" + + " }\n" + + "}\n") + .build(); MessageType message = (MessageType) schema.getType("Message"); JavaGenerator javaGenerator = JavaGenerator.get(schema); TypeSpec typeSpec = javaGenerator.generateType(message); - assertThat(JavaFile.builder("", typeSpec).build().toString()).contains("" - + " @WireField(\n" - + " tag = 1,\n" - + " keyAdapter = \"com.squareup.wire.ProtoAdapter#STRING\",\n" - + " adapter = \"Message$CdnResource#ADAPTER\"\n" - + " )\n" - + " public final Map templates;\n"); + assertThat(JavaFile.builder("", typeSpec).build().toString()) + .contains( + "" + + " @WireField(\n" + + " tag = 1,\n" + + " keyAdapter = \"com.squareup.wire.ProtoAdapter#STRING\",\n" + + " adapter = \"Message$CdnResource#ADAPTER\"\n" + + " )\n" + + " public final Map templates;\n"); } - @Test public void generateAbstractAdapter() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "package original.proto;\n" - + "option java_package = \"original.java\";\n" - + "import \"foo.proto\";\n" - + "message ProtoMessage {\n" - + " optional foo.proto.Foo field = 1;\n" - + " repeated int32 numbers = 3;\n" - + " optional foo.proto.CoinFlip coin_flip = 4;\n" - + " map bars = 2;\n" - + "}\n") - .add(Path.get("foo.proto"), "" - + "package foo.proto;\n" - + "option java_package = \"foo.java\";\n" - + "message Foo {\n" - + "}\n" - + "message Bar {\n" - + "}\n" - + "enum CoinFlip {\n" - + " HEADS = 1;\n" - + " TAILS = 2;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .withProfile("android.wire", "" - + "syntax = \"wire2\";\n" - + "import \"message.proto\";\n" - + "package original.proto;\n" - + "type original.proto.ProtoMessage {\n" - + " target target.java.JavaMessage using target.java.JavaMessage#ADAPTER;\n" - + "}\n") - .generateJava("original.proto.ProtoMessage", "android")).isEqualTo("" - + "package original.java;\n" - + "\n" - + "import com.squareup.wire.FieldEncoding;\n" - + "import com.squareup.wire.ProtoAdapter;\n" - + "import com.squareup.wire.ProtoReader;\n" - + "import com.squareup.wire.ProtoWriter;\n" - + "import com.squareup.wire.ReverseProtoWriter;\n" - + "import com.squareup.wire.Syntax;\n" - + "import com.squareup.wire.internal.Internal;\n" - + "import foo.java.Bar;\n" - + "import foo.java.CoinFlip;\n" - + "import foo.java.Foo;\n" - + "import java.io.IOException;\n" - + "import java.lang.Integer;\n" - + "import java.lang.Override;\n" - + "import java.lang.String;\n" - + "import java.util.List;\n" - + "import java.util.Map;\n" - + "import target.java.JavaMessage;\n" - + "\n" - + "public abstract class AbstractProtoMessageAdapter extends ProtoAdapter {\n" - + " private ProtoAdapter> bars;\n" - + "\n" - + " public AbstractProtoMessageAdapter() {\n" - + " super(FieldEncoding.LENGTH_DELIMITED, JavaMessage.class, \"type.googleapis.com/original.proto.ProtoMessage\", Syntax.PROTO_2, null, \"message.proto\");\n" - + " }\n" - + "\n" - + " public abstract Foo field(JavaMessage value);\n" - + "\n" - + " public abstract List numbers(JavaMessage value);\n" - + "\n" - + " public abstract CoinFlip coin_flip(JavaMessage value);\n" - + "\n" - + " public abstract Map bars(JavaMessage value);\n" - + "\n" - + " public abstract JavaMessage fromProto(Foo field, List numbers, CoinFlip coin_flip,\n" - + " Map bars);\n" - + "\n" - + " @Override\n" - + " public int encodedSize(JavaMessage value) {\n" - + " int result = 0;\n" - + " result += Foo.ADAPTER.encodedSizeWithTag(1, field(value));\n" - + " result += ProtoAdapter.INT32.asRepeated().encodedSizeWithTag(3, numbers(value));\n" - + " result += CoinFlip.ADAPTER.encodedSizeWithTag(4, coin_flip(value));\n" - + " result += barsAdapter().encodedSizeWithTag(2, bars(value));\n" - + " return result;\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void encode(ProtoWriter writer, JavaMessage value) throws IOException {\n" - + " Foo.ADAPTER.encodeWithTag(writer, 1, field(value));\n" - + " ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 3, numbers(value));\n" - + " CoinFlip.ADAPTER.encodeWithTag(writer, 4, coin_flip(value));\n" - + " barsAdapter().encodeWithTag(writer, 2, bars(value));\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void encode(ReverseProtoWriter writer, JavaMessage value) throws IOException {\n" - + " barsAdapter().encodeWithTag(writer, 2, bars(value));\n" - + " CoinFlip.ADAPTER.encodeWithTag(writer, 4, coin_flip(value));\n" - + " ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 3, numbers(value));\n" - + " Foo.ADAPTER.encodeWithTag(writer, 1, field(value));\n" - + " }\n" - + "\n" - + " @Override\n" - + " public JavaMessage decode(ProtoReader reader) throws IOException {\n" - + " Foo field = null;\n" - + " Map bars = Internal.newMutableMap();\n" - + " List numbers = Internal.newMutableList();\n" - + " CoinFlip coin_flip = null;\n" - + " long token = reader.beginMessage();\n" - + " for (int tag; (tag = reader.nextTag()) != -1;) {\n" - + " switch (tag) {\n" - + " case 1: field = Foo.ADAPTER.decode(reader); break;\n" - + " case 2: bars.putAll(barsAdapter().decode(reader)); break;\n" - + " case 3: numbers.add(ProtoAdapter.INT32.decode(reader)); break;\n" - + " case 4: {\n" - + " try {\n" - + " coin_flip = CoinFlip.ADAPTER.decode(reader);\n" - + " } catch (ProtoAdapter.EnumConstantNotFoundException ignored) {\n" - + " }\n" - + " break;\n" - + " }\n" - + " default: {\n" - + " reader.skip();\n" - + " }\n" - + " }\n" - + " }\n" - + " reader.endMessageAndGetUnknownFields(token);\n" - + " return fromProto(field, numbers, coin_flip, bars);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public JavaMessage redact(JavaMessage value) {\n" - + " return value;\n" - + " }\n" - + "\n" - + " private ProtoAdapter> barsAdapter() {\n" - + " ProtoAdapter> result = bars;\n" - + " if (result == null) {\n" - + " result = ProtoAdapter.newMapAdapter(ProtoAdapter.STRING, Bar.ADAPTER);\n" - + " bars = result;\n" - + " }\n" - + " return result;\n" - + " }\n" - + "}\n"); + @Test + public void generateAbstractAdapter() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "package original.proto;\n" + + "option java_package = \"original.java\";\n" + + "import \"foo.proto\";\n" + + "message ProtoMessage {\n" + + " optional foo.proto.Foo field = 1;\n" + + " repeated int32 numbers = 3;\n" + + " optional foo.proto.CoinFlip coin_flip = 4;\n" + + " map bars = 2;\n" + + "}\n") + .add( + Path.get("foo.proto"), + "" + + "package foo.proto;\n" + + "option java_package = \"foo.java\";\n" + + "message Foo {\n" + + "}\n" + + "message Bar {\n" + + "}\n" + + "enum CoinFlip {\n" + + " HEADS = 1;\n" + + " TAILS = 2;\n" + + "}\n") + .build(); + assertThat( + new JavaWithProfilesGenerator(schema) + .withProfile( + "android.wire", + "" + + "syntax = \"wire2\";\n" + + "import \"message.proto\";\n" + + "package original.proto;\n" + + "type original.proto.ProtoMessage {\n" + + " target target.java.JavaMessage using target.java.JavaMessage#ADAPTER;\n" + + "}\n") + .generateJava("original.proto.ProtoMessage", "android")) + .isEqualTo( + "" + + "package original.java;\n" + + "\n" + + "import com.squareup.wire.FieldEncoding;\n" + + "import com.squareup.wire.ProtoAdapter;\n" + + "import com.squareup.wire.ProtoReader;\n" + + "import com.squareup.wire.ProtoWriter;\n" + + "import com.squareup.wire.ReverseProtoWriter;\n" + + "import com.squareup.wire.Syntax;\n" + + "import com.squareup.wire.internal.Internal;\n" + + "import foo.java.Bar;\n" + + "import foo.java.CoinFlip;\n" + + "import foo.java.Foo;\n" + + "import java.io.IOException;\n" + + "import java.lang.Integer;\n" + + "import java.lang.Override;\n" + + "import java.lang.String;\n" + + "import java.util.List;\n" + + "import java.util.Map;\n" + + "import target.java.JavaMessage;\n" + + "\n" + + "public abstract class AbstractProtoMessageAdapter extends ProtoAdapter {\n" + + " private ProtoAdapter> bars;\n" + + "\n" + + " public AbstractProtoMessageAdapter() {\n" + + " super(FieldEncoding.LENGTH_DELIMITED, JavaMessage.class, \"type.googleapis.com/original.proto.ProtoMessage\", Syntax.PROTO_2, null, \"message.proto\");\n" + + " }\n" + + "\n" + + " public abstract Foo field(JavaMessage value);\n" + + "\n" + + " public abstract List numbers(JavaMessage value);\n" + + "\n" + + " public abstract CoinFlip coin_flip(JavaMessage value);\n" + + "\n" + + " public abstract Map bars(JavaMessage value);\n" + + "\n" + + " public abstract JavaMessage fromProto(Foo field, List numbers, CoinFlip coin_flip,\n" + + " Map bars);\n" + + "\n" + + " @Override\n" + + " public int encodedSize(JavaMessage value) {\n" + + " int result = 0;\n" + + " result += Foo.ADAPTER.encodedSizeWithTag(1, field(value));\n" + + " result += ProtoAdapter.INT32.asRepeated().encodedSizeWithTag(3, numbers(value));\n" + + " result += CoinFlip.ADAPTER.encodedSizeWithTag(4, coin_flip(value));\n" + + " result += barsAdapter().encodedSizeWithTag(2, bars(value));\n" + + " return result;\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void encode(ProtoWriter writer, JavaMessage value) throws IOException {\n" + + " Foo.ADAPTER.encodeWithTag(writer, 1, field(value));\n" + + " ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 3, numbers(value));\n" + + " CoinFlip.ADAPTER.encodeWithTag(writer, 4, coin_flip(value));\n" + + " barsAdapter().encodeWithTag(writer, 2, bars(value));\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void encode(ReverseProtoWriter writer, JavaMessage value) throws IOException {\n" + + " barsAdapter().encodeWithTag(writer, 2, bars(value));\n" + + " CoinFlip.ADAPTER.encodeWithTag(writer, 4, coin_flip(value));\n" + + " ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 3, numbers(value));\n" + + " Foo.ADAPTER.encodeWithTag(writer, 1, field(value));\n" + + " }\n" + + "\n" + + " @Override\n" + + " public JavaMessage decode(ProtoReader reader) throws IOException {\n" + + " Foo field = null;\n" + + " Map bars = Internal.newMutableMap();\n" + + " List numbers = Internal.newMutableList();\n" + + " CoinFlip coin_flip = null;\n" + + " long token = reader.beginMessage();\n" + + " for (int tag; (tag = reader.nextTag()) != -1;) {\n" + + " switch (tag) {\n" + + " case 1: field = Foo.ADAPTER.decode(reader); break;\n" + + " case 2: bars.putAll(barsAdapter().decode(reader)); break;\n" + + " case 3: numbers.add(ProtoAdapter.INT32.decode(reader)); break;\n" + + " case 4: {\n" + + " try {\n" + + " coin_flip = CoinFlip.ADAPTER.decode(reader);\n" + + " } catch (ProtoAdapter.EnumConstantNotFoundException ignored) {\n" + + " }\n" + + " break;\n" + + " }\n" + + " default: {\n" + + " reader.skip();\n" + + " }\n" + + " }\n" + + " }\n" + + " reader.endMessageAndGetUnknownFields(token);\n" + + " return fromProto(field, numbers, coin_flip, bars);\n" + + " }\n" + + "\n" + + " @Override\n" + + " public JavaMessage redact(JavaMessage value) {\n" + + " return value;\n" + + " }\n" + + "\n" + + " private ProtoAdapter> barsAdapter() {\n" + + " ProtoAdapter> result = bars;\n" + + " if (result == null) {\n" + + " result = ProtoAdapter.newMapAdapter(ProtoAdapter.STRING, Bar.ADAPTER);\n" + + " bars = result;\n" + + " }\n" + + " return result;\n" + + " }\n" + + "}\n"); } - @Test public void generateAbstractAdapterForEnum() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "package original.proto;\n" - + "message ProtoMessage {\n" - + " optional CoinFlip coin_flip = 1;\n" - + "}\n" - + "enum CoinFlip {\n" - + " // In Canada this is the Queen!\n" - + " HEADS = 1;\n" - + " TAILS = 2;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .withProfile("android.wire", "" - + "syntax = \"wire2\";\n" - + "import \"message.proto\";\n" - + "package original.proto;\n" - + "type original.proto.CoinFlip {\n" - + " target target.java.JavaCoinFlip using target.java.JavaCoinFlip#ADAPTER;\n" - + "}\n") - .generateJava("original.proto.CoinFlip", "android")).isEqualTo("" - + "package original.proto;\n" - + "\n" - + "import com.squareup.wire.FieldEncoding;\n" - + "import com.squareup.wire.ProtoAdapter;\n" - + "import com.squareup.wire.ProtoReader;\n" - + "import com.squareup.wire.ProtoWriter;\n" - + "import com.squareup.wire.ReverseProtoWriter;\n" - + "import java.io.IOException;\n" - + "import java.lang.Override;\n" - + "import java.net.ProtocolException;\n" - + "import target.java.JavaCoinFlip;\n" - + "\n" - + "public class CoinFlipAdapter extends ProtoAdapter {\n" - + " /**\n" - + " * In Canada this is the Queen!\n" - + " */\n" - + " protected final JavaCoinFlip HEADS;\n" - + "\n" - + " protected final JavaCoinFlip TAILS;\n" - + "\n" - + " public CoinFlipAdapter(JavaCoinFlip HEADS, JavaCoinFlip TAILS) {\n" - + " super(FieldEncoding.VARINT, JavaCoinFlip.class);\n" - + " this.HEADS = HEADS;\n" - + " this.TAILS = TAILS;\n" - + " }\n" - + "\n" - + " protected int toValue(JavaCoinFlip value) {\n" - + " if (value.equals(HEADS)) return 1;\n" - + " if (value.equals(TAILS)) return 2;\n" - + " return -1;\n" - + " }\n" - + "\n" - + " protected JavaCoinFlip fromValue(int value) {\n" - + " switch (value) {\n" - + " case 1: return HEADS;\n" - + " case 2: return TAILS;\n" - + " default: throw new ProtoAdapter.EnumConstantNotFoundException(value, JavaCoinFlip.class);\n" - + " }\n" - + " }\n" - + "\n" - + " @Override\n" - + " public int encodedSize(JavaCoinFlip value) {\n" - + " return ProtoAdapter.UINT32.encodedSize(toValue(value));\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void encode(ProtoWriter writer, JavaCoinFlip value) throws IOException {\n" - + " int i = toValue(value);\n" - + " if (i == -1) throw new ProtocolException(\"Unexpected enum constant: \" + value);\n" - + " writer.writeVarint32(i);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public void encode(ReverseProtoWriter writer, JavaCoinFlip value) throws IOException {\n" - + " int i = toValue(value);\n" - + " if (i == -1) throw new ProtocolException(\"Unexpected enum constant: \" + value);\n" - + " writer.writeVarint32(i);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public JavaCoinFlip decode(ProtoReader reader) throws IOException {\n" - + " int value = reader.readVarint32();\n" - + " return fromValue(value);\n" - + " }\n" - + "\n" - + " @Override\n" - + " public JavaCoinFlip redact(JavaCoinFlip value) {\n" - + " return value;\n" - + " }\n" - + "}\n"); + @Test + public void generateAbstractAdapterForEnum() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "package original.proto;\n" + + "message ProtoMessage {\n" + + " optional CoinFlip coin_flip = 1;\n" + + "}\n" + + "enum CoinFlip {\n" + + " // In Canada this is the Queen!\n" + + " HEADS = 1;\n" + + " TAILS = 2;\n" + + "}\n") + .build(); + assertThat( + new JavaWithProfilesGenerator(schema) + .withProfile( + "android.wire", + "" + + "syntax = \"wire2\";\n" + + "import \"message.proto\";\n" + + "package original.proto;\n" + + "type original.proto.CoinFlip {\n" + + " target target.java.JavaCoinFlip using target.java.JavaCoinFlip#ADAPTER;\n" + + "}\n") + .generateJava("original.proto.CoinFlip", "android")) + .isEqualTo( + "" + + "package original.proto;\n" + + "\n" + + "import com.squareup.wire.FieldEncoding;\n" + + "import com.squareup.wire.ProtoAdapter;\n" + + "import com.squareup.wire.ProtoReader;\n" + + "import com.squareup.wire.ProtoWriter;\n" + + "import com.squareup.wire.ReverseProtoWriter;\n" + + "import java.io.IOException;\n" + + "import java.lang.Override;\n" + + "import java.net.ProtocolException;\n" + + "import target.java.JavaCoinFlip;\n" + + "\n" + + "public class CoinFlipAdapter extends ProtoAdapter {\n" + + " /**\n" + + " * In Canada this is the Queen!\n" + + " */\n" + + " protected final JavaCoinFlip HEADS;\n" + + "\n" + + " protected final JavaCoinFlip TAILS;\n" + + "\n" + + " public CoinFlipAdapter(JavaCoinFlip HEADS, JavaCoinFlip TAILS) {\n" + + " super(FieldEncoding.VARINT, JavaCoinFlip.class);\n" + + " this.HEADS = HEADS;\n" + + " this.TAILS = TAILS;\n" + + " }\n" + + "\n" + + " protected int toValue(JavaCoinFlip value) {\n" + + " if (value.equals(HEADS)) return 1;\n" + + " if (value.equals(TAILS)) return 2;\n" + + " return -1;\n" + + " }\n" + + "\n" + + " protected JavaCoinFlip fromValue(int value) {\n" + + " switch (value) {\n" + + " case 1: return HEADS;\n" + + " case 2: return TAILS;\n" + + " default: throw new ProtoAdapter.EnumConstantNotFoundException(value, JavaCoinFlip.class);\n" + + " }\n" + + " }\n" + + "\n" + + " @Override\n" + + " public int encodedSize(JavaCoinFlip value) {\n" + + " return ProtoAdapter.UINT32.encodedSize(toValue(value));\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void encode(ProtoWriter writer, JavaCoinFlip value) throws IOException {\n" + + " int i = toValue(value);\n" + + " if (i == -1) throw new ProtocolException(\"Unexpected enum constant: \" + value);\n" + + " writer.writeVarint32(i);\n" + + " }\n" + + "\n" + + " @Override\n" + + " public void encode(ReverseProtoWriter writer, JavaCoinFlip value) throws IOException {\n" + + " int i = toValue(value);\n" + + " if (i == -1) throw new ProtocolException(\"Unexpected enum constant: \" + value);\n" + + " writer.writeVarint32(i);\n" + + " }\n" + + "\n" + + " @Override\n" + + " public JavaCoinFlip decode(ProtoReader reader) throws IOException {\n" + + " int value = reader.readVarint32();\n" + + " return fromValue(value);\n" + + " }\n" + + "\n" + + " @Override\n" + + " public JavaCoinFlip redact(JavaCoinFlip value) {\n" + + " return value;\n" + + " }\n" + + "}\n"); } - @Test public void generateAbstractAdapterWithRedactedField() throws IOException { - SchemaBuilder builder = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "import \"option_redacted.proto\";\n" - + "message ProtoMessage {\n" - + " optional string secret = 1 [(squareup.protos.redacted_option.redacted) = true];\n" - + "}\n"); + @Test + public void generateAbstractAdapterWithRedactedField() throws IOException { + SchemaBuilder builder = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "import \"option_redacted.proto\";\n" + + "message ProtoMessage {\n" + + " optional string secret = 1 [(squareup.protos.redacted_option.redacted) = true];\n" + + "}\n"); addFromTest(builder, Path.get("option_redacted.proto")); Schema schema = builder.build(); - assertThat(new JavaWithProfilesGenerator(schema) - .withProfile("android.wire", "" - + "syntax = \"wire2\";\n" - + "import \"message.proto\";\n" - + "type ProtoMessage {\n" - + " target JavaMessage using JavaMessage#ADAPTER;\n" - + "}\n") - .generateJava("ProtoMessage", "android")).contains("" - + " @Override\n" - + " public JavaMessage redact(JavaMessage value) {\n" - + " return null;\n" - + " }\n"); + assertThat( + new JavaWithProfilesGenerator(schema) + .withProfile( + "android.wire", + "" + + "syntax = \"wire2\";\n" + + "import \"message.proto\";\n" + + "type ProtoMessage {\n" + + " target JavaMessage using JavaMessage#ADAPTER;\n" + + "}\n") + .generateJava("ProtoMessage", "android")) + .contains( + "" + + " @Override\n" + + " public JavaMessage redact(JavaMessage value) {\n" + + " return null;\n" + + " }\n"); } - @Test public void nestedAbstractAdapterIsStatic() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message A {\n" - + " message B {\n" - + " optional string c = 1;\n" - + " }\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .withProfile("android.wire", "" - + "syntax = \"wire2\";\n" - + "import \"message.proto\";\n" - + "type A.B {\n" - + " target java.lang.String using AbAdapter#INSTANCE;\n" - + "}\n") - .generateJava("A", "android")).contains("" - + " public abstract static class AbstractBAdapter extends ProtoAdapter {\n"); + @Test + public void nestedAbstractAdapterIsStatic() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message A {\n" + + " message B {\n" + + " optional string c = 1;\n" + + " }\n" + + "}\n") + .build(); + assertThat( + new JavaWithProfilesGenerator(schema) + .withProfile( + "android.wire", + "" + + "syntax = \"wire2\";\n" + + "import \"message.proto\";\n" + + "type A.B {\n" + + " target java.lang.String using AbAdapter#INSTANCE;\n" + + "}\n") + .generateJava("A", "android")) + .contains( + "" + + " public abstract static class AbstractBAdapter extends ProtoAdapter {\n"); } + /** https://github.com/square/wire/issues/655 */ - @Test public void defaultValues() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message Message {\n" - + " optional int32 a = 1 [default = 10 ];\n" - + " optional int32 b = 2 [default = 0x20 ];\n" - + " optional int64 c = 3 [default = 11 ];\n" - + " optional int64 d = 4 [default = 0x21 ];\n" - + " optional float e = 5 [default = inf ];\n" - + " optional double f = 6 [default = -inf ];\n" - + " optional double g = 7 [default = nan ];\n" - + " optional double h = 8 [default = -nan ];\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("Message"); + @Test + public void defaultValues() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message Message {\n" + + " optional int32 a = 1 [default = 10 ];\n" + + " optional int32 b = 2 [default = 0x20 ];\n" + + " optional int64 c = 3 [default = 11 ];\n" + + " optional int64 d = 4 [default = 0x21 ];\n" + + " optional float e = 5 [default = inf ];\n" + + " optional double f = 6 [default = -inf ];\n" + + " optional double g = 7 [default = nan ];\n" + + " optional double h = 8 [default = -nan ];\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("Message"); assertThat(code).contains(" public static final Integer DEFAULT_A = 10;"); assertThat(code).contains(" public static final Integer DEFAULT_B = 32;"); assertThat(code).contains(" public static final Long DEFAULT_C = 11L;"); @@ -411,158 +467,190 @@ public final class JavaGeneratorTest { assertThat(code).contains(" public static final Double DEFAULT_H = Double.NaN;"); } - @Test public void defaultValuesMustNotBeOctal() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message Message {\n" - + " optional int32 a = 1 [default = 020 ];\n" - + " optional int64 b = 2 [default = 021 ];\n" - + "}\n") - .build(); + @Test + public void defaultValuesMustNotBeOctal() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message Message {\n" + + " optional int32 a = 1 [default = 020 ];\n" + + " optional int64 b = 2 [default = 021 ];\n" + + "}\n") + .build(); try { - new JavaWithProfilesGenerator(schema) - .generateJava("Message"); + new JavaWithProfilesGenerator(schema).generateJava("Message"); fail(); } catch (IllegalStateException expected) { assertThat(expected).hasMessageThat().contains("Octal literal unsupported: 020"); } } - @Test public void nullableFieldsWithoutParcelable() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message A {\n" - + " message B {\n" - + " optional string c = 1;\n" - + " }\n" - + "}\n") - .build(); + @Test + public void nullableFieldsWithoutParcelable() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message A {\n" + + " message B {\n" + + " optional string c = 1;\n" + + " }\n" + + "}\n") + .build(); MessageType message = (MessageType) schema.getType("A"); JavaGenerator javaGenerator = JavaGenerator.get(schema).withAndroidAnnotations(true); TypeSpec typeSpec = javaGenerator.generateType(message); - assertThat(JavaFile.builder("", typeSpec).build().toString()).contains("" - + " @WireField(\n" - + " tag = 1,\n" - + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" - + " )\n" - + " @Nullable\n" - + " public final String c;"); + assertThat(JavaFile.builder("", typeSpec).build().toString()) + .contains( + "" + + " @WireField(\n" + + " tag = 1,\n" + + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" + + " )\n" + + " @Nullable\n" + + " public final String c;"); } - @Test public void unsortedTagsPrintSchemaIndex() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message A {\n" - + " optional string two = 2;\n" - + " optional string one = 1;\n" - + "}\n") - .build(); + @Test + public void unsortedTagsPrintSchemaIndex() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message A {\n" + + " optional string two = 2;\n" + + " optional string one = 1;\n" + + "}\n") + .build(); MessageType message = (MessageType) schema.getType("A"); JavaGenerator javaGenerator = JavaGenerator.get(schema).withAndroidAnnotations(true); TypeSpec typeSpec = javaGenerator.generateType(message); String javaOutput = JavaFile.builder("", typeSpec).build().toString(); System.out.println(javaOutput); - assertThat(javaOutput).contains("" - + " @WireField(\n" - + " tag = 2,\n" - + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" - + " )\n" - + " @Nullable\n" - + " public final String two;"); - assertThat(javaOutput).contains("" - + " @WireField(\n" - + " tag = 1,\n" - + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" - + " )\n" - + " @Nullable\n" - + " public final String one;"); + assertThat(javaOutput) + .contains( + "" + + " @WireField(\n" + + " tag = 2,\n" + + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" + + " )\n" + + " @Nullable\n" + + " public final String two;"); + assertThat(javaOutput) + .contains( + "" + + " @WireField(\n" + + " tag = 1,\n" + + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" + + " )\n" + + " @Nullable\n" + + " public final String one;"); } - @Test public void androidSupport() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message A {\n" - + " message B {\n" - + " optional string c = 1;\n" - + " }\n" - + "}\n") - .build(); + @Test + public void androidSupport() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message A {\n" + + " message B {\n" + + " optional string c = 1;\n" + + " }\n" + + "}\n") + .build(); MessageType message = (MessageType) schema.getType("A"); JavaGenerator javaGenerator = JavaGenerator.get(schema).withAndroid(true); TypeSpec typeSpec = javaGenerator.generateType(message); String javaOutput = JavaFile.builder("", typeSpec).build().toString(); - assertThat(javaOutput).contains("" - + " @WireField(\n" - + " tag = 1,\n" - + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" - + " )\n" - + " public final String c;"); - assertThat(javaOutput).contains("" - + "public static final Parcelable.Creator CREATOR = AndroidMessage.newCreator(ADAPTER)"); + assertThat(javaOutput) + .contains( + "" + + " @WireField(\n" + + " tag = 1,\n" + + " adapter = \"com.squareup.wire.ProtoAdapter#STRING\"\n" + + " )\n" + + " public final String c;"); + assertThat(javaOutput) + .contains( + "" + + "public static final Parcelable.Creator CREATOR = AndroidMessage.newCreator(ADAPTER)"); } @Test public void enclosingTypeIsNotMessage() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "message A {\n" - + " message B {\n" - + " }\n" - + " optional B b = 1;\n" - + "}\n") - .build(); - - Schema pruned = schema.prune(new PruningRules.Builder() - .addRoot("A.B") - .build()); + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "message A {\n" + + " message B {\n" + + " }\n" + + " optional B b = 1;\n" + + "}\n") + .build(); + + Schema pruned = schema.prune(new PruningRules.Builder().addRoot("A.B").build()); JavaGenerator javaGenerator = JavaGenerator.get(schema); TypeSpec typeSpec = javaGenerator.generateType(pruned.getType("A")); String javaOutput = JavaFile.builder("", typeSpec).build().toString(); assertThat(javaOutput) - .contains("" - + "public final class A {\n" - + " private A() {\n" - + " throw new AssertionError();\n" - + " }"); + .contains( + "" + + "public final class A {\n" + + " private A() {\n" + + " throw new AssertionError();\n" + + " }"); assertThat(javaOutput).contains("public static final class B extends Message {"); } @Test public void generateTypeUsesPackageNameOnFieldAndClassNameClash() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("person.proto"), "" - + "package common.proto;\n" - + "enum Gender {\n" - + " Gender_Male = 0;\n" - + " Gender_Female = 1;\n" - + "}\n" - + "message Person {\n" - + " optional Gender Gender = 1;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .generateJava("common.proto.Person")) + Schema schema = + new SchemaBuilder() + .add( + Path.get("person.proto"), + "" + + "package common.proto;\n" + + "enum Gender {\n" + + " Gender_Male = 0;\n" + + " Gender_Female = 1;\n" + + "}\n" + + "message Person {\n" + + " optional Gender Gender = 1;\n" + + "}\n") + .build(); + assertThat(new JavaWithProfilesGenerator(schema).generateJava("common.proto.Person")) .contains("public final Gender common_proto_Gender;"); } @Test public void buildersOnlyGeneratesNonPublicConstructors() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("message.proto"), "" - + "syntax = \"proto2\";\n" - + "message SomeMessage {\n" - + " optional string a = 1;\n" - + " optional string b = 2;\n" - + " message InnerMessage {\n" - + " optional string c = 3;\n" - + " optional string d = 8;\n" - + " }\n" - + "}\n" - ) - .build(); - String javaOutput = new JavaWithProfilesGenerator(schema) - .generateJava("SomeMessage", null /* profileName */, true /* buildersOnly */); + Schema schema = + new SchemaBuilder() + .add( + Path.get("message.proto"), + "" + + "syntax = \"proto2\";\n" + + "message SomeMessage {\n" + + " optional string a = 1;\n" + + " optional string b = 2;\n" + + " message InnerMessage {\n" + + " optional string c = 3;\n" + + " optional string d = 8;\n" + + " }\n" + + "}\n") + .build(); + String javaOutput = + new JavaWithProfilesGenerator(schema) + .generateJava("SomeMessage", null /* profileName */, true /* buildersOnly */); assertThat(javaOutput).contains(" SomeMessage("); assertThat(javaOutput).contains(" InnerMessage("); assertThat(javaOutput).doesNotContain("public SomeMessage("); @@ -571,232 +659,264 @@ public void buildersOnlyGeneratesNonPublicConstructors() throws Exception { @Test public void generateTypeUsesPackageNameOnFieldAndClassNameClashWithinPackage() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("a.proto"), "" - + "package common.proto;\n" - + "enum Status {\n" - + " Status_Approved = 0;\n" - + " Status_Denied = 1;\n" - + "}\n" - + "enum AnotherStatus {\n" - + " AnotherStatus_Processing = 0;\n" - + " AnotherStatus_Completed = 1;\n" - + "}\n" - + "message A {\n" - + " message B {\n" - + " optional Status Status = 1;\n" - + " }\n" - + " repeated B b = 1;" - + " optional AnotherStatus Status = 2;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .generateJava("common.proto.A")) + Schema schema = + new SchemaBuilder() + .add( + Path.get("a.proto"), + "" + + "package common.proto;\n" + + "enum Status {\n" + + " Status_Approved = 0;\n" + + " Status_Denied = 1;\n" + + "}\n" + + "enum AnotherStatus {\n" + + " AnotherStatus_Processing = 0;\n" + + " AnotherStatus_Completed = 1;\n" + + "}\n" + + "message A {\n" + + " message B {\n" + + " optional Status Status = 1;\n" + + " }\n" + + " repeated B b = 1;" + + " optional AnotherStatus Status = 2;\n" + + "}\n") + .build(); + assertThat(new JavaWithProfilesGenerator(schema).generateJava("common.proto.A")) .contains("public final AnotherStatus common_proto_Status;"); } - @Test public void fieldHasScalarName() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("example.proto"), "" - + "package squareup.testing.wire;\n" - + "\n" - + "option java_package = \"com.squareup.testing.wire\";\n" - + "\n" - + "message Data {\n" - + " optional string string = 1;\n" - + " repeated string values = 2;\n" - + "}\n") - .build(); - assertThat(new JavaWithProfilesGenerator(schema) - .generateJava("squareup.testing.wire.Data")).contains("" - + " public Builder string(String string) {\n" - + " this.string = string;\n" - + " return this;\n" - + " }"); + @Test + public void fieldHasScalarName() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("example.proto"), + "" + + "package squareup.testing.wire;\n" + + "\n" + + "option java_package = \"com.squareup.testing.wire\";\n" + + "\n" + + "message Data {\n" + + " optional string string = 1;\n" + + " repeated string values = 2;\n" + + "}\n") + .build(); + assertThat(new JavaWithProfilesGenerator(schema).generateJava("squareup.testing.wire.Data")) + .contains( + "" + + " public Builder string(String string) {\n" + + " this.string = string;\n" + + " return this;\n" + + " }"); } - @Test public void sanitizeStringsOnPrinting() throws Exception { - Schema schema = new SchemaBuilder() - .add(Path.get("example.proto"), "" - + "message Person {\n" - + " required string name = 1;\n" - + " required int32 id = 2;\n" - + " repeated PhoneNumber phone = 3;\n" - + " repeated string aliases = 4;\n" - + "\n" - + " message PhoneNumber {\n" - + " required string number = 1;\n" - + " optional PhoneType type = 2 [default = HOME];\n" - + " }\n" - + " enum PhoneType {\n" - + " HOME = 0;\n" - + " WORK = 1;\n" - + " MOBILE = 2;\n" - + " }\n" - + "}\n") - .build(); - String generatedCode = new JavaWithProfilesGenerator(schema) - .generateJava("Person"); - assertThat(generatedCode).contains("" - + " public String toString() {\n" - + " StringBuilder builder = new StringBuilder();\n" - + " builder.append(\", name=\").append(Internal.sanitize(name));\n" - + " builder.append(\", id=\").append(id);\n" - + " if (!phone.isEmpty()) builder.append(\", phone=\").append(phone);\n" - + " if (!aliases.isEmpty()) builder.append(\", aliases=\").append(Internal.sanitize(aliases));\n" - + " return builder.replace(0, 2, \"Person{\").append('}').toString();\n" - + " }"); - assertThat(generatedCode).contains("" - + " public String toString() {\n" - + " StringBuilder builder = new StringBuilder();\n" - + " builder.append(\", number=\").append(Internal.sanitize(number));\n" - + " if (type != null) builder.append(\", type=\").append(type);\n" - + " return builder.replace(0, 2, \"PhoneNumber{\").append('}').toString();\n" - + " }"); + @Test + public void sanitizeStringsOnPrinting() throws Exception { + Schema schema = + new SchemaBuilder() + .add( + Path.get("example.proto"), + "" + + "message Person {\n" + + " required string name = 1;\n" + + " required int32 id = 2;\n" + + " repeated PhoneNumber phone = 3;\n" + + " repeated string aliases = 4;\n" + + "\n" + + " message PhoneNumber {\n" + + " required string number = 1;\n" + + " optional PhoneType type = 2 [default = HOME];\n" + + " }\n" + + " enum PhoneType {\n" + + " HOME = 0;\n" + + " WORK = 1;\n" + + " MOBILE = 2;\n" + + " }\n" + + "}\n") + .build(); + String generatedCode = new JavaWithProfilesGenerator(schema).generateJava("Person"); + assertThat(generatedCode) + .contains( + "" + + " public String toString() {\n" + + " StringBuilder builder = new StringBuilder();\n" + + " builder.append(\", name=\").append(Internal.sanitize(name));\n" + + " builder.append(\", id=\").append(id);\n" + + " if (!phone.isEmpty()) builder.append(\", phone=\").append(phone);\n" + + " if (!aliases.isEmpty()) builder.append(\", aliases=\").append(Internal.sanitize(aliases));\n" + + " return builder.replace(0, 2, \"Person{\").append('}').toString();\n" + + " }"); + assertThat(generatedCode) + .contains( + "" + + " public String toString() {\n" + + " StringBuilder builder = new StringBuilder();\n" + + " builder.append(\", number=\").append(Internal.sanitize(number));\n" + + " if (type != null) builder.append(\", type=\").append(type);\n" + + " return builder.replace(0, 2, \"PhoneNumber{\").append('}').toString();\n" + + " }"); } - @Test public void wirePackageTakesPrecedenceOverJavaPackage() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "import \"wire/extensions.proto\";\n" - + "\n" - + "option java_package = \"java_package\";\n" - + "option (wire.wire_package) = \"wire_package\";\n" - + "\n" - + "message Person {\n" - + " required string name = 1;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Person"); + @Test + public void wirePackageTakesPrecedenceOverJavaPackage() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "import \"wire/extensions.proto\";\n" + + "\n" + + "option java_package = \"java_package\";\n" + + "option (wire.wire_package) = \"wire_package\";\n" + + "\n" + + "message Person {\n" + + " required string name = 1;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Person"); assertThat(code).contains("package wire_package"); assertThat(code).contains("class Person"); } - @Test public void wirePackageTakesPrecedenceOverProtoPackage() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "import \"wire/extensions.proto\";\n" - + "\n" - + "option (wire.wire_package) = \"wire_package\";\n" - + "\n" - + "message Person {\n" - + " required string name = 1;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Person"); + @Test + public void wirePackageTakesPrecedenceOverProtoPackage() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "import \"wire/extensions.proto\";\n" + + "\n" + + "option (wire.wire_package) = \"wire_package\";\n" + + "\n" + + "message Person {\n" + + " required string name = 1;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Person"); assertThat(code).contains("package wire_package"); assertThat(code).contains("class Person"); } - @Test public void packageNameUsedIfFieldNameIsSameAsNonScalarTypeName() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("common/common_message.proto"), - "package a.Common;\n" - + "option java_package = \"a.common\";" - + "message CommonMessage {\n" - + " required string First = 1;\n" - + "}\n") - .add(Path.get("example.proto"), - "package a;\n" - + "import \"common/common_message.proto\";\n" - + "\n" - + "message Example {\n" - + " required Common.CommonMessage CommonMessage = 1;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("a.Example"); + @Test + public void packageNameUsedIfFieldNameIsSameAsNonScalarTypeName() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("common/common_message.proto"), + "package a.Common;\n" + + "option java_package = \"a.common\";" + + "message CommonMessage {\n" + + " required string First = 1;\n" + + "}\n") + .add( + Path.get("example.proto"), + "package a;\n" + + "import \"common/common_message.proto\";\n" + + "\n" + + "message Example {\n" + + " required Common.CommonMessage CommonMessage = 1;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("a.Example"); assertThat(code).contains("package a"); assertThat(code).contains("import a.common.CommonMessage"); assertThat(code).contains("public CommonMessage a_CommonMessage"); } - @Test public void wirePackageUsedInImport() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "import \"wire/extensions.proto\";\n" - + "\n" - + "option (wire.wire_package) = \"wire_package\";\n" - + "\n" - + "message Person {\n" - + " required string name = 1;\n" - + "}\n") - .add(Path.get("city_package/home.proto"), - "package city_package;\n" - + "import \"proto_package/person.proto\";\n" - + "\n" - + "message Home {\n" - + " repeated proto_package.Person person = 1;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("city_package.Home"); + @Test + public void wirePackageUsedInImport() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "import \"wire/extensions.proto\";\n" + + "\n" + + "option (wire.wire_package) = \"wire_package\";\n" + + "\n" + + "message Person {\n" + + " required string name = 1;\n" + + "}\n") + .add( + Path.get("city_package/home.proto"), + "package city_package;\n" + + "import \"proto_package/person.proto\";\n" + + "\n" + + "message Home {\n" + + " repeated proto_package.Person person = 1;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("city_package.Home"); assertThat(code).contains("package city_package"); assertThat(code).contains("import wire_package.Person"); } - @Test public void deprecatedEnum() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "enum Direction {\n" - + " option deprecated = true;\n" - + " NORTH = 1;\n" - + " EAST = 2;\n" - + " SOUTH = 3;\n" - + " WEST = 4;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Direction"); + @Test + public void deprecatedEnum() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "enum Direction {\n" + + " option deprecated = true;\n" + + " NORTH = 1;\n" + + " EAST = 2;\n" + + " SOUTH = 3;\n" + + " WEST = 4;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Direction"); assertThat(code).contains("@Deprecated\npublic enum Direction"); } - @Test public void deprecatedEnumConstant() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "enum Direction {\n" - + " NORTH = 1;\n" - + " EAST = 2 [deprecated = true];\n" - + " SOUTH = 3;\n" - + " WEST = 4;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Direction"); + @Test + public void deprecatedEnumConstant() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "enum Direction {\n" + + " NORTH = 1;\n" + + " EAST = 2 [deprecated = true];\n" + + " SOUTH = 3;\n" + + " WEST = 4;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Direction"); assertThat(code).contains(" @Deprecated\n EAST(2)"); } - @Test public void deprecatedField() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "message Person {\n" - + " optional string name = 1 [deprecated = true];\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Person"); + @Test + public void deprecatedField() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "message Person {\n" + + " optional string name = 1 [deprecated = true];\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Person"); assertThat(code).contains(" @Deprecated\n public final String name;"); } - @Test public void deprecatedMessage() throws IOException { - Schema schema = new SchemaBuilder() - .add(Path.get("proto_package/person.proto"), - "package proto_package;\n" - + "message Person {\n" - + " option deprecated = true;\n" - + " optional string name = 1;\n" - + "}\n") - .build(); - String code = new JavaWithProfilesGenerator(schema) - .generateJava("proto_package.Person"); + @Test + public void deprecatedMessage() throws IOException { + Schema schema = + new SchemaBuilder() + .add( + Path.get("proto_package/person.proto"), + "package proto_package;\n" + + "message Person {\n" + + " option deprecated = true;\n" + + " optional string name = 1;\n" + + "}\n") + .build(); + String code = new JavaWithProfilesGenerator(schema).generateJava("proto_package.Person"); assertThat(code).contains("@Deprecated\npublic final class Person"); } } diff --git a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt index 49c07b7490..3bfd85053b 100644 --- a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt +++ b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt @@ -1,11 +1,11 @@ /* - * Copyright (C) 2022 Block, Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -47,7 +47,9 @@ internal class JavaWithProfilesGenerator(private val schema: Schema) { return if (profileName == null) Profile() else profiles["$profileName.wire"]!! } - @Throws(IOException::class) @JvmOverloads fun generateJava( + @Throws(IOException::class) + @JvmOverloads + fun generateJava( typeName: String, profileName: String? = null, buildersOnly: Boolean = false, diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/FieldExtensions.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/FieldExtensions.kt index c8569ad0db..ec1ca38bb7 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/FieldExtensions.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/FieldExtensions.kt @@ -1,11 +1,11 @@ /* - * Copyright 2019 Square Inc. + * Copyright (C) 2019 Square, Inc. * * 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 + * https://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, @@ -13,10 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * Extension functions/properties for the Field class - */ package com.squareup.wire.kotlin import com.squareup.wire.schema.Field diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt index bba8787b51..5a523cd290 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt @@ -1,11 +1,11 @@ /* - * Copyright 2018 Square Inc. + * Copyright (C) 2018 Square, Inc. * * 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 + * https://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, @@ -108,11 +108,11 @@ import com.squareup.wire.schema.internal.javaPackage import com.squareup.wire.schema.internal.legacyQualifiedFieldName import com.squareup.wire.schema.internal.optionValueToInt import com.squareup.wire.schema.internal.optionValueToLong +import java.util.Locale import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import okio.ByteString import okio.ByteString.Companion.encode -import java.util.Locale class KotlinGenerator private constructor( val schema: Schema, @@ -212,7 +212,7 @@ class KotlinGenerator private constructor( fun generatedServiceName( service: Service, rpc: Rpc? = null, - isImplementation: Boolean = false + isImplementation: Boolean = false, ): ClassName { val typeName = service.serviceName as ClassName val simpleName = buildString { @@ -275,8 +275,9 @@ class KotlinGenerator private constructor( if (rpcRole == RpcRole.CLIENT) { val (implementationName, implementationSpec) = generateService( - service, onlyRpc, - isImplementation = true + service, + onlyRpc, + isImplementation = true, ) result[implementationName] = implementationSpec } @@ -303,7 +304,7 @@ class KotlinGenerator private constructor( private fun generateService( service: Service, onlyRpc: Rpc?, - isImplementation: Boolean + isImplementation: Boolean, ): Pair { check(rpcRole == RpcRole.CLIENT || !isImplementation) { "only clients may generate implementations" @@ -318,12 +319,12 @@ class KotlinGenerator private constructor( .primaryConstructor( FunSpec.constructorBuilder() .addParameter("client", GrpcClient::class) - .build() + .build(), ) .addProperty( PropertySpec.builder("client", GrpcClient::class, PRIVATE) .initializer("client") - .build() + .build(), ) .addSuperinterface(interfaceName) } @@ -343,8 +344,11 @@ class KotlinGenerator private constructor( for (rpc in rpcs) { builder.addFunction( generateRpcFunction( - rpc, service.name, service.type.enclosingTypeOrPackage, isImplementation - ) + rpc, + service.name, + service.type.enclosingTypeOrPackage, + isImplementation, + ), ) } @@ -356,7 +360,7 @@ class KotlinGenerator private constructor( rpc: Rpc, serviceName: String, servicePackageName: String?, - isImplementation: Boolean + isImplementation: Boolean, ): FunSpec { val packageName = if (servicePackageName.isNullOrBlank()) "" else "$servicePackageName." val funSpecBuilder = FunSpec.builder(rpc.name) @@ -421,7 +425,7 @@ class KotlinGenerator private constructor( rpc.requestStreaming || rpc.responseStreaming -> { funSpecBuilder .returns( - GrpcStreamingCall::class.asClassName().parameterizedBy(requestType, responseType) + GrpcStreamingCall::class.asClassName().parameterizedBy(requestType, responseType), ) if (isImplementation) { funSpecBuilder @@ -434,7 +438,7 @@ class KotlinGenerator private constructor( else -> { funSpecBuilder .returns( - GrpcCall::class.asClassName().parameterizedBy(requestType, responseType) + GrpcCall::class.asClassName().parameterizedBy(requestType, responseType), ) if (isImplementation) { funSpecBuilder @@ -558,7 +562,7 @@ class KotlinGenerator private constructor( addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "${className.simpleName} is deprecated") - .build() + .build(), ) } } @@ -595,7 +599,7 @@ class KotlinGenerator private constructor( companionBuilder.addProperty( PropertySpec.builder("serialVersionUID", LONG, PRIVATE, CONST) .initializer("0L") - .build() + .build(), ) classBuilder.addType(companionBuilder.build()) @@ -641,7 +645,7 @@ class KotlinGenerator private constructor( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "Shouldn't be used in Kotlin") .addMember("level = %T.%L", DeprecationLevel::class, DeprecationLevel.HIDDEN) - .build() + .build(), ) .returns(NOTHING) .addStatement("throw %T(%S)", ClassName("kotlin", "AssertionError"), "Builders are deprecated and only available in a javaInterop build; see https://square.github.io/wire/wire_compiler/#kotlin") @@ -808,7 +812,7 @@ class KotlinGenerator private constructor( result.addParameter( ParameterSpec.builder(fieldName, fieldOrOneOf.typeNameForMessageField) .defaultValue("this.%N", fieldName) - .build() + .build(), ) fieldNames += fieldName } @@ -818,7 +822,7 @@ class KotlinGenerator private constructor( result.addParameter( ParameterSpec.builder(fieldName, fieldClass) .defaultValue("this.%N", fieldName) - .build() + .build(), ) fieldNames += fieldName } @@ -828,13 +832,13 @@ class KotlinGenerator private constructor( result.addParameter( ParameterSpec.builder("unknownFields", ByteString::class) .defaultValue("this.unknownFields") - .build() + .build(), ) fieldNames += "unknownFields" result.addStatement( "return %L", fieldNames - .joinToString(prefix = className.simpleName + "(", postfix = ")") + .joinToString(prefix = className.simpleName + "(", postfix = ")"), ) return result.build() } @@ -842,12 +846,12 @@ class KotlinGenerator private constructor( private fun generateBuilderClass( type: MessageType, className: ClassName, - builderClassName: ClassName + builderClassName: ClassName, ): TypeSpec { val builder = TypeSpec.classBuilder("Builder") .superclass( Message.Builder::class.asTypeName() - .parameterizedBy(className, builderClassName) + .parameterizedBy(className, builderClassName), ) if (!javaInterOp) { @@ -855,20 +859,20 @@ class KotlinGenerator private constructor( .primaryConstructor( FunSpec.constructorBuilder() .addParameter("message", className) - .build() + .build(), ) .addProperty( PropertySpec.builder("message", className) .addModifiers(PRIVATE) .initializer("message") - .build() + .build(), ) .addFunction( FunSpec.builder("build") .addModifiers(OVERRIDE) .returns(className) .addStatement("return message") - .build() + .build(), ) .build() } @@ -953,8 +957,8 @@ class KotlinGenerator private constructor( type, boxOneOf, nameAllocator, - builderClass - ) + builderClass, + ), ) } @@ -972,7 +976,7 @@ class KotlinGenerator private constructor( field: Field, nameAllocator: NameAllocator, builderType: TypeName, - oneOf: OneOf? + oneOf: OneOf?, ): FunSpec { val fieldName = nameAllocator[field] val funBuilder = FunSpec.builder(fieldName) @@ -985,7 +989,7 @@ class KotlinGenerator private constructor( funBuilder.addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "$fieldName is deprecated") - .build() + .build(), ) } if (field.isRepeated && !field.useArray) { @@ -1058,7 +1062,7 @@ class KotlinGenerator private constructor( constructorBuilder.addParameter( ParameterSpec.builder(unknownFields, byteClass) .defaultValue("%T.EMPTY", byteClass) - .build() + .build(), ) classBuilder.primaryConstructor(constructorBuilder.build()) @@ -1066,7 +1070,7 @@ class KotlinGenerator private constructor( private fun parametersAndProperties( message: MessageType, - nameAllocator: NameAllocator + nameAllocator: NameAllocator, ): List> { val result = mutableListOf>() @@ -1079,14 +1083,14 @@ class KotlinGenerator private constructor( field = fieldOrOneOf, nameAllocator = nameAllocator, schemaIndex = schemaIndex++, - ) + ), ) is OneOf -> result.add( constructorParameterAndProperty( message = message, oneOf = fieldOrOneOf, nameAllocator = nameAllocator, - ) + ), ) else -> throw IllegalArgumentException("Unexpected element: $fieldOrOneOf") } @@ -1115,7 +1119,7 @@ class KotlinGenerator private constructor( "%M(%S, %N)", MemberName("com.squareup.wire.internal", "immutableCopyOfMapWithStructValues"), fieldName, - fieldName + fieldName, ) } field.type!!.isStruct -> { @@ -1123,7 +1127,7 @@ class KotlinGenerator private constructor( "%M(%S, %N)", MemberName("com.squareup.wire.internal", "immutableCopyOfStruct"), fieldName, - fieldName + fieldName, ) } field.isPacked && field.isScalar && field.useArray -> { @@ -1134,7 +1138,7 @@ class KotlinGenerator private constructor( "%M(%S, %N)", MemberName("com.squareup.wire.internal", "immutableCopyOf"), fieldName, - fieldName + fieldName, ) } else -> CodeBlock.of("%N", fieldName) @@ -1147,7 +1151,7 @@ class KotlinGenerator private constructor( addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "$fieldName is deprecated") - .build() + .build(), ) } for (annotation in optionAnnotations(field.options)) { @@ -1170,7 +1174,7 @@ class KotlinGenerator private constructor( private fun constructorParameterAndProperty( message: MessageType, oneOf: OneOf, - nameAllocator: NameAllocator + nameAllocator: NameAllocator, ): Pair { val fieldClass = message.oneOfClassFor(oneOf, nameAllocator) val fieldName = nameAllocator[oneOf] @@ -1214,13 +1218,17 @@ class KotlinGenerator private constructor( EncodeMode.REQUIRED -> WireField.Label.REQUIRED EncodeMode.OMIT_IDENTITY -> { // Wrapper types don't omit identity values on JSON as other proto3 messages would. - if (field.type!!.isWrapper) null - else WireField.Label.OMIT_IDENTITY + if (field.type!!.isWrapper) { + null + } else { + WireField.Label.OMIT_IDENTITY + } } EncodeMode.REPEATED -> WireField.Label.REPEATED EncodeMode.PACKED -> WireField.Label.PACKED EncodeMode.MAP, - EncodeMode.NULL_IF_ABSENT -> null + EncodeMode.NULL_IF_ABSENT, + -> null } if (wireFieldLabel != null) { addMember("label = %T.%L", WireField.Label::class, wireFieldLabel) @@ -1288,7 +1296,8 @@ class KotlinGenerator private constructor( } } addStatement( - "%N += %P", resultName, + "%N += %P", + resultName, buildCodeBlock { add(fieldName) if (fieldOrOneOf.isRedacted) { @@ -1306,14 +1315,15 @@ class KotlinGenerator private constructor( add(fieldName) } } - } + }, ) } is OneOf -> { val fieldName = localNameAllocator[fieldOrOneOf] add("if (%N != null) ", fieldName) addStatement( - "%N += %P", resultName, + "%N += %P", + resultName, buildCodeBlock { add(fieldName) if (fieldOrOneOf.fields.any { it.isRedacted }) { @@ -1322,7 +1332,7 @@ class KotlinGenerator private constructor( add("=\$") add(fieldName) } - } + }, ) } else -> throw IllegalArgumentException("Unexpected element: $fieldOrOneOf") @@ -1334,7 +1344,7 @@ class KotlinGenerator private constructor( resultName, className.simpleName + "{", ", ", - "}" + "}", ) } } @@ -1348,7 +1358,7 @@ class KotlinGenerator private constructor( private fun addDefaultFields( type: MessageType, companionBuilder: TypeSpec.Builder, - nameAllocator: NameAllocator + nameAllocator: NameAllocator, ) { for (field in type.fieldsAndFlatOneOfFieldsAndBoxedOneOfs().filterIsInstance()) { val default = field.default ?: continue @@ -1366,7 +1376,7 @@ class KotlinGenerator private constructor( } } .initializer(fieldValue) - .build() + .build(), ) } } @@ -1395,7 +1405,7 @@ class KotlinGenerator private constructor( typeName == ByteString::class.asTypeName() -> CodeBlock.of( "%S.%M()!!", defaultValue.toString().encode(charset = Charsets.ISO_8859_1).base64(), - ByteString.Companion::class.asClassName().member("decodeBase64") + ByteString.Companion::class.asClassName().member("decodeBase64"), ) protoType.isEnum -> CodeBlock.of("%T.%L", typeName, defaultValue) else -> throw IllegalStateException("$protoType is not an allowed scalar type") @@ -1496,13 +1506,13 @@ class KotlinGenerator private constructor( .superclass(ProtoAdapter::class.asClassName().parameterizedBy(parentClassName)) .addSuperclassConstructorParameter( "\n⇥%T.LENGTH_DELIMITED", - FieldEncoding::class.asClassName() + FieldEncoding::class.asClassName(), ) .addSuperclassConstructorParameter("\n%T::class", parentClassName) .addSuperclassConstructorParameter("\n%S", type.type.typeUrl!!) .addSuperclassConstructorParameter( "\n%M", - MemberName(Syntax::class.asClassName(), type.syntax.name) + MemberName(Syntax::class.asClassName(), type.syntax.name), ) .addSuperclassConstructorParameter("\nnull") .addSuperclassConstructorParameter("\n%S\n⇤", type.location.path) @@ -1524,7 +1534,7 @@ class KotlinGenerator private constructor( PropertySpec.builder(adapterName, adapterType) .jvmField() .initializer("%L", adapterObject.build()) - .build() + .build(), ) } @@ -1532,7 +1542,7 @@ class KotlinGenerator private constructor( val adapterType = ProtoAdapter::class.asTypeName() .parameterizedBy( Map::class.asTypeName() - .parameterizedBy(keyType.typeName, valueType.typeName) + .parameterizedBy(keyType.typeName, valueType.typeName), ) // Map adapters have to be lazy in order to avoid a circular reference when its value type @@ -1543,7 +1553,7 @@ class KotlinGenerator private constructor( MemberName("kotlin", "lazy"), ProtoAdapter::class, keyType.getAdapterName(), - valueType.getAdapterName() + valueType.getAdapterName(), ) .build() } @@ -1563,8 +1573,11 @@ class KotlinGenerator private constructor( add(fieldEqualsIdentityBlock(fieldOrOneOf, fieldName)) } addStatement( - "%N += %L.encodedSizeWithTag(%L, value.%L)", sizeName, adapterFor(fieldOrOneOf), - fieldOrOneOf.tag, fieldName + "%N += %L.encodedSizeWithTag(%L, value.%L)", + sizeName, + adapterFor(fieldOrOneOf), + fieldOrOneOf.tag, + fieldName, ) } is OneOf -> { @@ -1625,7 +1638,7 @@ class KotlinGenerator private constructor( "%L.encodeWithTag(writer, %L, value.%L)", adapterFor(field), field.tag, - fieldName + fieldName, ) } } @@ -1699,7 +1712,7 @@ class KotlinGenerator private constructor( " ?: throw %1M(%2L, %3S)", missingRequiredFields, fieldName, - fieldOrOneOf.name + fieldOrOneOf.name, ) } else { CodeBlock.of("") @@ -1747,8 +1760,9 @@ class KotlinGenerator private constructor( addStatement("%L", decodeAndAssign(field, fieldName, adapterName)) nextControlFlow("catch (e: %T)", ProtoAdapter.EnumConstantNotFoundException::class) addStatement( - "reader.addUnknownField(%L, %T.VARINT, e.value.toLong())", tag, - FieldEncoding::class + "reader.addUnknownField(%L, %T.VARINT, e.value.toLong())", + tag, + FieldEncoding::class, ) endControlFlow() } @@ -1798,7 +1812,7 @@ class KotlinGenerator private constructor( val decode = if (field.useArray) { CodeBlock.of( "%M(reader)", - MemberName("com.squareup.wire.internal", "decodePrimitive_${field.type!!.simpleName}") + MemberName("com.squareup.wire.internal", "decodePrimitive_${field.type!!.simpleName}"), ) } else { CodeBlock.of( @@ -1851,10 +1865,12 @@ class KotlinGenerator private constructor( return when (type) { ProtoType.FLOAT, ProtoType.FIXED32, - ProtoType.SFIXED32 -> 4 + ProtoType.SFIXED32, + -> 4 ProtoType.DOUBLE, ProtoType.FIXED64, - ProtoType.SFIXED64 -> 8 + ProtoType.SFIXED64, + -> 8 // If we aren't 100% confident in the size of the field, we assume the worst case scenario of 1 byte which gives // us the maximum possible number of elements in the list. else -> 1 @@ -1877,10 +1893,14 @@ class KotlinGenerator private constructor( ClassName("kotlin", "UnsupportedOperationException"), requiredRedactedMessageFields.joinToString( prefix = if (requiredRedactedMessageFields.size > 1) "Fields [" else "Field '", - postfix = if (requiredRedactedMessageFields.size > 1) "] are " else "' is " + - "required and cannot be redacted.", - transform = nameAllocator::get - ) + postfix = if (requiredRedactedMessageFields.size > 1) { + "] are " + } else { + "' is " + + "required and cannot be redacted." + }, + transform = nameAllocator::get, + ), ) return result.build() } @@ -1907,7 +1927,7 @@ class KotlinGenerator private constructor( return result .addStatement( "return %L", - redactedFields.joinToCode(separator = ",\n", prefix = "value.copy(\n⇥", suffix = "\n⇤)") + redactedFields.joinToCode(separator = ",\n", prefix = "value.copy(\n⇥", suffix = "\n⇤)"), ) .build() } @@ -1958,13 +1978,16 @@ class KotlinGenerator private constructor( adapterConstant != null -> { CodeBlock.of( "%T%L%L", - adapterConstant.kotlinClassName, adapterFieldDelimiterName, adapterConstant.memberName + adapterConstant.kotlinClassName, + adapterFieldDelimiterName, + adapterConstant.memberName, ) } isScalar -> { CodeBlock.of( "%T$adapterFieldDelimiterName%L", - ProtoAdapter::class, simpleName.uppercase(Locale.US) + ProtoAdapter::class, + simpleName.uppercase(Locale.US), ) } this == ProtoType.DURATION -> { @@ -2075,7 +2098,7 @@ class KotlinGenerator private constructor( addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "${type.simpleName} is deprecated") - .build() + .build(), ) } } @@ -2083,7 +2106,7 @@ class KotlinGenerator private constructor( .addProperty( PropertySpec.builder(valueName, Int::class, OVERRIDE) .initializer(valueName) - .build() + .build(), ) .addType(generateEnumCompanion(enum)) @@ -2109,11 +2132,11 @@ class KotlinGenerator private constructor( addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "${constant.name} is deprecated") - .build() + .build(), ) } } - .build() + .build(), ) } @@ -2125,7 +2148,8 @@ class KotlinGenerator private constructor( val format = when (field.type) { // Special case for doubles and floats because of negative zeros. ProtoType.DOUBLE, - ProtoType.FLOAT -> "if (!value.%1L.equals(%2L)) " + ProtoType.FLOAT, + -> "if (!value.%1L.equals(%2L)) " else -> "if (value.%1L != %2L) " } return CodeBlock.of(format, fieldName, field.identityValue) @@ -2178,7 +2202,7 @@ class KotlinGenerator private constructor( .addSuperclassConstructorParameter("\n⇥%T::class", parentClassName) .addSuperclassConstructorParameter( "\n%M", - MemberName(Syntax::class.asClassName(), message.syntax.name) + MemberName(Syntax::class.asClassName(), message.syntax.name), ) .addSuperclassConstructorParameter("\n%L\n⇤", message.identity()) .addFunction( @@ -2187,7 +2211,7 @@ class KotlinGenerator private constructor( .addParameter(valueName, Int::class) .returns(parentClassName.copy(nullable = true)) .addStatement("return %T.fromValue(value)", parentClassName) - .build() + .build(), ) .build() @@ -2217,7 +2241,7 @@ class KotlinGenerator private constructor( PropertySpec.builder(creatorName, creatorTypeName) .jvmField() .initializer("%T.newCreator(ADAPTER)", ANDROID_MESSAGE) - .build() + .build(), ) } @@ -2240,7 +2264,7 @@ class KotlinGenerator private constructor( */ fun generateOptionType( extend: Extend, - field: Field + field: Field, ): TypeSpec? { require(field in extend.fields) val annotationTargets = extend.annotationTargets @@ -2273,7 +2297,7 @@ class KotlinGenerator private constructor( .addAnnotation( AnnotationSpec.builder(Retention::class) .addMember("%T.%L", AnnotationRetention::class, AnnotationRetention.RUNTIME) - .build() + .build(), ) .addAnnotation( AnnotationSpec.builder(Target::class) @@ -2283,7 +2307,7 @@ class KotlinGenerator private constructor( } this } - .build() + .build(), ) if (field.documentation.isNotEmpty()) { builder.addKdoc("%L\n", field.documentation) @@ -2291,12 +2315,12 @@ class KotlinGenerator private constructor( builder.primaryConstructor( FunSpec.constructorBuilder() .addParameter("value", returnType) - .build() + .build(), ) builder.addProperty( PropertySpec.builder("value", returnType, PUBLIC) .initializer("value") - .build() + .build(), ) return builder.build() } @@ -2307,7 +2331,8 @@ class KotlinGenerator private constructor( isRepeated -> CodeBlock.of("val $allocatedName = mutableListOf<%T>()", type!!.typeName) isMap -> CodeBlock.of( "val $allocatedName = mutableMapOf<%T, %T>()", - keyType.typeName, valueType.typeName + keyType.typeName, + valueType.typeName, ) else -> CodeBlock.of("var $allocatedName: %T = %L", typeNameForBuilderField, identityValue) } @@ -2402,7 +2427,7 @@ class KotlinGenerator private constructor( type is MessageType -> CodeBlock.of("null") type is EnumType -> type.identity() else -> throw IllegalArgumentException( - "Unexpected type $protoType for IDENTITY_IF_ABSENT" + "Unexpected type $protoType for IDENTITY_IF_ABSENT", ) } } @@ -2418,7 +2443,8 @@ class KotlinGenerator private constructor( EncodeMode.MAP, EncodeMode.REPEATED, EncodeMode.PACKED, - EncodeMode.REQUIRED -> false + EncodeMode.REQUIRED, + -> false EncodeMode.NULL_IF_ABSENT -> true EncodeMode.OMIT_IDENTITY -> { when { @@ -2487,10 +2513,10 @@ class KotlinGenerator private constructor( .addParameter("tag", Int::class) .addParameter("adapter", ProtoAdapter::class.asClassName().parameterizedBy(typeVariable)) .addParameter("declaredName", String::class) - .build() + .build(), ) .superclass( - com.squareup.wire.OneOf.Key::class.asClassName().parameterizedBy(typeVariable) + com.squareup.wire.OneOf.Key::class.asClassName().parameterizedBy(typeVariable), ) .addSuperclassConstructorParameter("%L", "tag") .addSuperclassConstructorParameter("%L", "adapter") @@ -2502,10 +2528,10 @@ class KotlinGenerator private constructor( .returns( com.squareup.wire.OneOf::class.asClassName().parameterizedBy( boxClassName.parameterizedBy(typeVariable), - typeVariable - ) + typeVariable, + ), ) - .build() + .build(), ) .addFunction( FunSpec.builder("decode") @@ -2513,11 +2539,11 @@ class KotlinGenerator private constructor( .returns( com.squareup.wire.OneOf::class.asClassName().parameterizedBy( boxClassName.parameterizedBy(typeVariable), - typeVariable - ) + typeVariable, + ), ) .addStatement("return create(%L.decode(%L))", "adapter", "reader") - .build() + .build(), ) .build() } @@ -2548,14 +2574,14 @@ class KotlinGenerator private constructor( val allKeys = PropertySpec .builder( keysFieldName, - Set::class.asClassName().parameterizedBy(boxClassName.parameterizedBy(STAR)) + Set::class.asClassName().parameterizedBy(boxClassName.parameterizedBy(STAR)), ) .addAnnotation(ClassName("com.squareup.wire.internal", "JvmStatic")) .initializer( CodeBlock.of( """setOf(${keyFieldNames.map { "%L" }.joinToString(", ")})""", - *keyFieldNames.toTypedArray() - ) + *keyFieldNames.toTypedArray(), + ), ) .build() companionBuilder.addProperty(allKeys) @@ -2581,7 +2607,7 @@ class KotlinGenerator private constructor( addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember("message = %S", "${field.name} is deprecated") - .build() + .build(), ) } for (annotation in optionAnnotations(field.options)) { @@ -2598,8 +2624,8 @@ class KotlinGenerator private constructor( "adapter", field.getAdapterName(), "declaredName", - field.name - ) + field.name, + ), ) .build() } @@ -2696,12 +2722,13 @@ class KotlinGenerator private constructor( ProtoType.INT32 to CodeBlock.of("0"), ProtoType.SFIXED32 to CodeBlock.of("0"), ProtoType.SINT32 to CodeBlock.of("0"), - ProtoType.UINT32 to CodeBlock.of("0") + ProtoType.UINT32 to CodeBlock.of("0"), ) private val MESSAGE = Message::class.asClassName() private val ANDROID_MESSAGE = MESSAGE.peerClass("AndroidMessage") - @JvmStatic @JvmName("get") + @JvmStatic + @JvmName("get") operator fun invoke( schema: Schema, profile: Profile = Profile(), @@ -2739,9 +2766,11 @@ class KotlinGenerator private constructor( } putAllExtensions( - schema, protoFile, - protoFile.types, protoFile.extendList, - memberToKotlinName + schema, + protoFile, + protoFile.types, + protoFile.extendList, + memberToKotlinName, ) } @@ -2771,7 +2800,7 @@ class KotlinGenerator private constructor( protoFile: ProtoFile, types: List, extendList: List, - memberToKotlinName: MutableMap + memberToKotlinName: MutableMap, ) { for (extend in extendList) { if (extend.annotationTargets.isEmpty()) continue @@ -2783,9 +2812,11 @@ class KotlinGenerator private constructor( } for (type in types) { putAllExtensions( - schema, protoFile, - type.nestedTypes, type.nestedExtendList, - memberToKotlinName + schema, + protoFile, + type.nestedTypes, + type.nestedExtendList, + memberToKotlinName, ) } } @@ -2824,4 +2855,5 @@ class KotlinGenerator private constructor( } private fun PropertySpec.Builder.jvmField(): PropertySpec.Builder = addAnnotation( - ClassName("com.squareup.wire.internal", "JvmField")) + ClassName("com.squareup.wire.internal", "JvmField"), +) diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinSchemaHandler.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinSchemaHandler.kt index efb8b2ba42..5abcff21ee 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinSchemaHandler.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinSchemaHandler.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.kotlin import com.squareup.kotlinpoet.ClassName @@ -10,8 +25,8 @@ import com.squareup.wire.schema.Schema import com.squareup.wire.schema.SchemaHandler import com.squareup.wire.schema.Service import com.squareup.wire.schema.Type -import okio.Path import java.io.IOException +import okio.Path class KotlinSchemaHandler( private val outDirectory: String, @@ -100,7 +115,7 @@ class KotlinSchemaHandler( val map = kotlinGenerator.generateServiceTypeSpecs(service, rpc) for ((className, typeSpec) in map) { generatedPaths.add( - write(className, typeSpec, service.type, service.location, context) + write(className, typeSpec, service.type, service.location, context), ) } } diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcCallStyle.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcCallStyle.kt index ea6e4760ee..577613e0b4 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcCallStyle.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcCallStyle.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -20,5 +20,5 @@ enum class RpcCallStyle { SUSPENDING, /** Generate blocking APIs callable by Java and Kotlin. */ - BLOCKING; + BLOCKING, } diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcRole.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcRole.kt index 0a7275b0fe..8fe01602ed 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcRole.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/RpcRole.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -24,5 +24,4 @@ enum class RpcRole { /** Doesn't generate any interfaces. */ NONE, - ; } diff --git a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt index a7eaebe9f1..256f232bf5 100644 --- a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt +++ b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt @@ -5,7 +5,7 @@ * 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 + * https://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, @@ -22,12 +22,12 @@ import com.squareup.wire.buildSchema import com.squareup.wire.kotlin.KotlinGenerator.Companion.sanitizeKdoc import com.squareup.wire.schema.PruningRules import com.squareup.wire.schema.addFromTest -import okio.Path.Companion.toPath import kotlin.test.Test import kotlin.test.assertContains import kotlin.test.assertEquals import kotlin.test.assertTrue import kotlin.text.RegexOption.DOT_MATCHES_ALL +import okio.Path.Companion.toPath class KotlinGeneratorTest { @Test fun basic() { @@ -49,7 +49,8 @@ class KotlinGeneratorTest { | optional PhoneType type = 2 [default = HOME]; | } | repeated PhoneNumber phone = 4; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Person").replace("\n", "") @@ -59,7 +60,7 @@ class KotlinGeneratorTest { assertThat(code).contains("PhoneNumber::class") assertThat(code).contains("override fun encode(writer: ProtoWriter, `value`: Person)") assertTrue( - code.contains("enum class PhoneType( override val `value`: Int, ) : WireEnum") + code.contains("enum class PhoneType( override val `value`: Int, ) : WireEnum"), ) assertThat(code).contains("fun fromValue(`value`: Int): PhoneType?") assertThat(code).contains("WORK(1),") @@ -87,7 +88,8 @@ class KotlinGeneratorTest { | optional double n = 14 [default = -inf]; | optional double o = 15 [default = nan]; | optional double p = 16 [default = -nan]; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Message") @@ -103,7 +105,7 @@ class KotlinGeneratorTest { assertThat(code).contains("const val DEFAULT_J: Double = -0.01") assertThat(code).contains( "public const val DEFAULT_K: Double\n" + - " = -1_230_000_000_000_000_000_000_000_000_000_000_000_000_000_000.0" + " = -1_230_000_000_000_000_000_000_000_000_000_000_000_000_000_000.0", ) assertThat(code).contains("const val DEFAULT_L: Double = 255.0") assertThat(code).contains("const val DEFAULT_M: Double = Double.POSITIVE_INFINITY") @@ -121,7 +123,8 @@ class KotlinGeneratorTest { | required float when = 1; | required int32 ADAPTER = 2; | optional int64 adapter = 3; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Message") @@ -144,7 +147,8 @@ class KotlinGeneratorTest { | message B { | } | optional B b = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } @@ -173,7 +177,8 @@ class KotlinGeneratorTest { | */ | public fun GetFeature(): GrpcCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide | @@ -196,7 +201,8 @@ class KotlinGeneratorTest { | responseAdapter = Feature.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -211,12 +217,13 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide"), ) } @@ -259,15 +266,17 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expected), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -311,15 +320,17 @@ class KotlinGeneratorTest { |} |$pointMessage |$routeSummaryMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expected), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -364,15 +375,17 @@ class KotlinGeneratorTest { |$pointMessage |$rectangeMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expected), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -420,15 +433,17 @@ class KotlinGeneratorTest { |$pointMessage |$rectangeMessage |$routeNoteMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expected), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -478,15 +493,17 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expected), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -504,7 +521,8 @@ class KotlinGeneratorTest { | */ | public fun GetFeature(): GrpcCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |import com.squareup.wire.GrpcCall |import com.squareup.wire.GrpcClient @@ -525,7 +543,8 @@ class KotlinGeneratorTest { | responseAdapter = Feature.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -540,12 +559,13 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("RouteGuide"), ) } @@ -565,7 +585,8 @@ class KotlinGeneratorTest { | */ | public fun GetFeature(): GrpcCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide.grpc | @@ -588,7 +609,8 @@ class KotlinGeneratorTest { | responseAdapter = Feature.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -605,12 +627,13 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.grpc.RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.grpc.RouteGuide"), ) } @@ -630,7 +653,8 @@ class KotlinGeneratorTest { | */ | public fun RecordRoute(): GrpcStreamingCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide | @@ -654,7 +678,8 @@ class KotlinGeneratorTest { | responseAdapter = RouteSummary.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -671,12 +696,13 @@ class KotlinGeneratorTest { |} |$pointMessage |$routeSummaryMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide"), ) } @@ -696,7 +722,8 @@ class KotlinGeneratorTest { | */ | public fun ListFeatures(): GrpcStreamingCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide | @@ -720,7 +747,8 @@ class KotlinGeneratorTest { | responseAdapter = Feature.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -738,12 +766,13 @@ class KotlinGeneratorTest { |$rectangeMessage |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide"), ) } @@ -904,7 +933,8 @@ class KotlinGeneratorTest { |} |$pointMessage |$routeNoteMessage - |""".trimMargin() + | + """.trimMargin(), ) } @@ -912,29 +942,33 @@ class KotlinGeneratorTest { listOf(blockingClientInterface, blockingClientImplementation), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.CLIENT - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.CLIENT, + ), ) assertEquals( listOf(blockingServer), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.BLOCKING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.BLOCKING, + rpcRole = RpcRole.SERVER, + ), ) assertEquals( listOf(suspendingClientInterface, suspendingClientImplementation), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.SUSPENDING, rpcRole = RpcRole.CLIENT - ) + rpcCallStyle = RpcCallStyle.SUSPENDING, + rpcRole = RpcRole.CLIENT, + ), ) assertEquals( listOf(suspendingServer), KotlinWithProfilesGenerator(schema).generateGrpcKotlin( "routeguide.RouteGuide", - rpcCallStyle = RpcCallStyle.SUSPENDING, rpcRole = RpcRole.SERVER - ) + rpcCallStyle = RpcCallStyle.SUSPENDING, + rpcRole = RpcRole.SERVER, + ), ) } @@ -960,7 +994,8 @@ class KotlinGeneratorTest { | */ | public fun RouteChat(): GrpcStreamingCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide | @@ -994,7 +1029,8 @@ class KotlinGeneratorTest { | responseAdapter = RouteNote.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -1014,12 +1050,13 @@ class KotlinGeneratorTest { |$pointMessage |$featureMessage |$routeNoteMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( listOf(expectedInterface, expectedImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide"), ) } @@ -1037,7 +1074,8 @@ class KotlinGeneratorTest { |$pointMessage |$featureMessage |$routeNoteMessage - |""".trimMargin() + | + """.trimMargin(), ) } @@ -1050,7 +1088,8 @@ class KotlinGeneratorTest { |public interface RouteGuideGetFeatureClient : Service { | public fun GetFeature(): GrpcCall |} - |""".trimMargin() + | + """.trimMargin() val expectedGetFeatureImplementation = """ |package routeguide | @@ -1067,11 +1106,12 @@ class KotlinGeneratorTest { | responseAdapter = Feature.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() assertEquals( listOf(expectedGetFeatureInterface, expectedGetFeatureImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide", "GetFeature") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide", "GetFeature"), ) val expectedRouteChatInterface = """ @@ -1083,7 +1123,8 @@ class KotlinGeneratorTest { |public interface RouteGuideRouteChatClient : Service { | public fun RouteChat(): GrpcStreamingCall |} - |""".trimMargin() + | + """.trimMargin() val expectedRouteChatImplementation = """ |package routeguide | @@ -1101,11 +1142,12 @@ class KotlinGeneratorTest { | responseAdapter = RouteNote.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() assertEquals( listOf(expectedRouteChatInterface, expectedRouteChatImplementation), - KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide", "RouteChat") + KotlinWithProfilesGenerator(schema).generateGrpcKotlin("routeguide.RouteGuide", "RouteChat"), ) } @@ -1132,7 +1174,8 @@ class KotlinGeneratorTest { | ) | public suspend fun GetFeature(request: Point): Feature |} - |""".trimMargin() + | + """.trimMargin() //language=kotlin val blockingInterface = """ @@ -1156,7 +1199,8 @@ class KotlinGeneratorTest { | ) | public fun GetFeature(request: Point): Feature |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -1173,7 +1217,8 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } @@ -1184,7 +1229,7 @@ class KotlinGeneratorTest { rpcRole = RpcRole.SERVER, rpcCallStyle = RpcCallStyle.SUSPENDING, nameSuffix = "", - ) + ), ) assertEquals( @@ -1194,7 +1239,7 @@ class KotlinGeneratorTest { rpcRole = RpcRole.SERVER, rpcCallStyle = RpcCallStyle.BLOCKING, nameSuffix = "Thing", - ) + ), ) } @@ -1205,7 +1250,8 @@ class KotlinGeneratorTest { """ |message Message { | required float tag = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Message") @@ -1222,7 +1268,8 @@ class KotlinGeneratorTest { """ |message Message { | required float var = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Message") @@ -1241,7 +1288,8 @@ class KotlinGeneratorTest { |} |message Person { | optional Gender Gender = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("common.proto.Person") @@ -1268,7 +1316,8 @@ class KotlinGeneratorTest { | } | repeated B b = 1; | optional AnotherStatus Status = 2; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("common.proto.A") @@ -1284,7 +1333,8 @@ class KotlinGeneratorTest { |import "google/protobuf/any.proto"; |message Message { | optional google.protobuf.Any just_one = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("common.proto.Message") @@ -1310,7 +1360,8 @@ class KotlinGeneratorTest { | optional PhoneType type = 2 [default = HOME]; | } | repeated PhoneNumber phone = 4; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Person").replace("\n", "") @@ -1320,7 +1371,7 @@ class KotlinGeneratorTest { assertThat(code).contains("PhoneNumber::class") assertThat(code).contains("override fun encode(writer: ProtoWriter, `value`: Person)") assertTrue( - code.contains("enum class PhoneType( override val `value`: Int, ) : WireEnum") + code.contains("enum class PhoneType( override val `value`: Int, ) : WireEnum"), ) assertThat(code).contains("fun fromValue(`value`: Int): PhoneType?") assertThat(code).contains("WORK(1),") @@ -1346,7 +1397,8 @@ class KotlinGeneratorTest { | WORK = 1; | MOBILE = 2; | } - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Person") @@ -1382,7 +1434,8 @@ class KotlinGeneratorTest { """ |message $longType { | required string $longMember = 1; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin(longType) @@ -1390,7 +1443,7 @@ class KotlinGeneratorTest { | ($longMember | != | other.$longMember) - """.trimMargin() + """.trimMargin() assertThat(code).contains("return false") assertThat(code).contains("return $longType(") @@ -1424,7 +1477,8 @@ class KotlinGeneratorTest { | } | message Baz {} |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("common.proto.LabelMessage") @@ -1451,7 +1505,8 @@ class KotlinGeneratorTest { |message Person { | required string name = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Person") @@ -1472,7 +1527,8 @@ class KotlinGeneratorTest { |message Person { | required string name = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Person") @@ -1493,7 +1549,8 @@ class KotlinGeneratorTest { |message Person { | required string name = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) add( "city_package/home.proto".toPath(), @@ -1504,7 +1561,8 @@ class KotlinGeneratorTest { |message Home { | repeated proto_package.Person person = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("city_package.Home") @@ -1523,7 +1581,8 @@ class KotlinGeneratorTest { |message Person { | repeated float info = 1 [packed = true, wire.use_array = true]; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Person") @@ -1549,7 +1608,7 @@ class KotlinGeneratorTest { | // g [h.i.j] k | CONSTANT = 0; |} - """.trimMargin() + """.trimMargin(), ) } val messageCode = KotlinWithProfilesGenerator(schema).generateKotlin("Message") @@ -1578,7 +1637,8 @@ class KotlinGeneratorTest { | */ | public fun GetFeature(): GrpcCall |} - |""".trimMargin() + | + """.trimMargin() val expectedImplementation = """ |package routeguide | @@ -1605,7 +1665,8 @@ class KotlinGeneratorTest { | responseAdapter = PropertiesFeatureAdapter.ADAPTER | )) |} - |""".trimMargin() + | + """.trimMargin() val schema = buildSchema { add( @@ -1620,7 +1681,8 @@ class KotlinGeneratorTest { |} |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } assertEquals( @@ -1639,9 +1701,10 @@ class KotlinGeneratorTest { |type routeguide.Feature { | target java.util.Properties using com.example.PropertiesFeatureAdapter#ADAPTER; |} - |""".trimMargin() + | + """.trimMargin(), ) - .generateGrpcKotlin("routeguide.RouteGuide", profileName = "java") + .generateGrpcKotlin("routeguide.RouteGuide", profileName = "java"), ) } @@ -1654,7 +1717,8 @@ class KotlinGeneratorTest { | |$pointMessage |$featureMessage - |""".trimMargin() + | + """.trimMargin(), ) } @@ -1668,7 +1732,8 @@ class KotlinGeneratorTest { |type routeguide.Point { | target kotlin.String using com.example.StringPointAdapter#INSTANCE; |} - |""".trimMargin() + | + """.trimMargin(), ) .generateKotlin("routeguide.Feature", profileName = "java") assertThat(kotlin).contains( @@ -1679,7 +1744,7 @@ class KotlinGeneratorTest { | schemaIndex = 1, | ) | public val location: String? = null, - """.trimMargin() + """.trimMargin(), ) assertThat(kotlin).contains( """ @@ -1689,7 +1754,7 @@ class KotlinGeneratorTest { | size += StringPointAdapter.INSTANCE.encodedSizeWithTag(2, value.location) | return size | } - """.trimMargin() + """.trimMargin(), ) assertThat(kotlin).contains( """ @@ -1698,7 +1763,7 @@ class KotlinGeneratorTest { | StringPointAdapter.INSTANCE.encodeWithTag(writer, 2, value.location) | writer.writeBytes(value.unknownFields) | } - """.trimMargin() + """.trimMargin(), ) assertThat(kotlin).contains( """ @@ -1718,7 +1783,8 @@ class KotlinGeneratorTest { | unknownFields = unknownFields | ) | } - |""".trimMargin() + | + """.trimMargin(), ) } @@ -1735,14 +1801,15 @@ class KotlinGeneratorTest { | SOUTH = 3; | WEST = 4; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Direction") assertThat(code).contains( """|@Deprecated(message = "Direction is deprecated") |public enum class Direction( - """.trimMargin() + """.trimMargin(), ) } @@ -1758,18 +1825,19 @@ class KotlinGeneratorTest { | SOUTH = 3; | WEST = 4; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Direction") assertThat(code).contains( """| @Deprecated(message = "EAST is deprecated") | EAST(2), - """.trimMargin() + """.trimMargin(), ) assertThat(code).contains( """| 2 -> @Suppress("DEPRECATION") EAST - """.trimMargin() + """.trimMargin(), ) } @@ -1782,7 +1850,8 @@ class KotlinGeneratorTest { |message Person { | optional string name = 1 [deprecated = true]; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Person") @@ -1794,7 +1863,7 @@ class KotlinGeneratorTest { | schemaIndex = 0, | ) | public val name: String? = null, - """.trimMargin() + """.trimMargin(), ) } @@ -1808,14 +1877,15 @@ class KotlinGeneratorTest { | option deprecated = true; | optional string name = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("proto_package.Person") assertThat(code).contains( """|@Deprecated(message = "Person is deprecated") |public class Person( - """.trimMargin() + """.trimMargin(), ) } @@ -1838,7 +1908,8 @@ class KotlinGeneratorTest { |} | |message SecretData {} - |""".trimMargin() + | + """.trimMargin(), ) addFromTest("option_redacted.proto".toPath()) } @@ -1858,7 +1929,7 @@ class KotlinGeneratorTest { | secret_data = null, | unknownFields = ByteString.EMPTY | ) - """.trimMargin() + """.trimMargin(), ) } @@ -1877,7 +1948,8 @@ class KotlinGeneratorTest { | optional string d = 8; | } |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema) @@ -1898,24 +1970,25 @@ class KotlinGeneratorTest { |message SomeMessage { | optional string a = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } assertThat( KotlinWithProfilesGenerator(schema) - .generateKotlin("SomeMessage", javaInterop = false) + .generateKotlin("SomeMessage", javaInterop = false), ) .contains("Builders are deprecated and only available in a javaInterop build") assertThat( KotlinWithProfilesGenerator(schema) - .generateKotlin("SomeMessage", javaInterop = true) + .generateKotlin("SomeMessage", javaInterop = true), ) .doesNotContain("Builders are deprecated and only available in a javaInterop build") // If `buildersOnly` is set to true, it takes precedence over `javaInterop` for it would // otherwise create non-instantiable types. assertThat( KotlinWithProfilesGenerator(schema) - .generateKotlin("SomeMessage", javaInterop = false, buildersOnly = true) + .generateKotlin("SomeMessage", javaInterop = false, buildersOnly = true), ) .doesNotContain("Builders are deprecated and only available in a javaInterop build") } @@ -1949,7 +2022,8 @@ class KotlinGeneratorTest { |} | |message SecretData {} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("SomeMessage", boxOneOfsMinSize = 3) @@ -2015,7 +2089,7 @@ class KotlinGeneratorTest { | ) | public val k: String? = null, | unknownFields: ByteString = ByteString.EMPTY, - """.trimMargin() + """.trimMargin(), ) } @@ -2042,7 +2116,7 @@ class KotlinGeneratorTest { |message OtherText { | string otherValue = 1; |} - """.trimMargin() + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("SomeText") @@ -2068,7 +2142,7 @@ class KotlinGeneratorTest { | ordinal = 2; | open = 3; |} - """.trimMargin() + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("ConflictingEnumConstants") @@ -2085,7 +2159,7 @@ class KotlinGeneratorTest { | @WireEnumConstant(declaredName = "open") | open_(3), | ; - """.trimMargin() + """.trimMargin(), ) assertThat(code).contains( """ @@ -2096,7 +2170,7 @@ class KotlinGeneratorTest { | 3 -> open_ | else -> null | } - """.trimMargin() + """.trimMargin(), ) } @@ -2107,7 +2181,8 @@ class KotlinGeneratorTest { """ |message Embedding { | repeated float values = 1 [packed = true]; - |}""".trimMargin() + |} + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema).generateKotlin("Embedding") @@ -2133,7 +2208,8 @@ class KotlinGeneratorTest { |message Person { | required string name = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) add( "employer_proto_package/employer.proto".toPath(), @@ -2144,7 +2220,8 @@ class KotlinGeneratorTest { |message Employer { | repeated person_proto_package.Person employees = 1; |} - |""".trimMargin() + | + """.trimMargin(), ) } val code = KotlinWithProfilesGenerator(schema) @@ -2157,25 +2234,29 @@ class KotlinGeneratorTest { |message Point { | optional int32 latitude = 1; | optional int32 longitude = 2; - |}""".trimMargin() + |} + """.trimMargin() private val rectangeMessage = """ |message Rectangle { | optional Point lo = 1; | optional Point hi = 2; - |}""".trimMargin() + |} + """.trimMargin() private val featureMessage = """ |message Feature { | optional string name = 1; | optional Point location = 2; - |}""".trimMargin() + |} + """.trimMargin() private val routeNoteMessage = """ |message RouteNote { | optional Point location = 1; | optional string message = 2; - |}""".trimMargin() + |} + """.trimMargin() private val routeSummaryMessage = """ |message RouteSummary { @@ -2183,6 +2264,7 @@ class KotlinGeneratorTest { | optional int32 feature_count = 2; | optional int32 distance = 3; | optional int32 elapsed_time = 4; - |}""".trimMargin() + |} + """.trimMargin() } } diff --git a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt index c7d97a19a7..838138c59b 100644 --- a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt +++ b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt @@ -1,11 +1,11 @@ /* - * Copyright (C) 2022 Block, Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, diff --git a/wire-moshi-adapter/build.gradle.kts b/wire-moshi-adapter/build.gradle.kts index 4d20ba11a9..8f28e0a13b 100644 --- a/wire-moshi-adapter/build.gradle.kts +++ b/wire-moshi-adapter/build.gradle.kts @@ -1,3 +1,4 @@ +import com.diffplug.gradle.spotless.SpotlessExtension import com.vanniktech.maven.publish.JavadocJar.Dokka import com.vanniktech.maven.publish.KotlinJvm import com.vanniktech.maven.publish.MavenPublishBaseExtension @@ -17,6 +18,21 @@ if (project.rootProject.name == "wire") { KotlinJvm(javadocJar = Dokka("dokkaGfm"), sourcesJar = true) ) } + + configure { + kotlin { + targetExclude( + // Generated files. + "src/test/java/**/*.kt", + ) + } + java { + targetExclude( + // Generated files. + "src/test/java/**/*.java", + ) + } + } } dependencies { diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/AnyMessageJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/AnyMessageJsonAdapter.kt index c5968287d5..e49c827372 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/AnyMessageJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/AnyMessageJsonAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -24,7 +24,7 @@ import java.io.IOException internal class AnyMessageJsonAdapter( private val moshi: Moshi, - private val typeUrlToAdapter: Map> + private val typeUrlToAdapter: Map>, ) : JsonAdapter() { @Throws(IOException::class) diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/EnumJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/EnumJsonAdapter.kt index 6f8abe5725..0e32c8f29b 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/EnumJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/EnumJsonAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt index 6107b3bca4..dd7c906fcb 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2018 Square Inc. + * Copyright (C) 2018 Square, Inc. * * 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 + * https://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, @@ -50,7 +50,7 @@ internal class MessageJsonAdapter, B : Message.Builder>( messageAdapter.writeAllFields( message = message, jsonAdapters = jsonAdapters, - redactedFieldsAdapter = redactedFieldsAdapter + redactedFieldsAdapter = redactedFieldsAdapter, ) { name, value, jsonAdapter -> out.name(name) jsonAdapter.toJson(out, value) diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt index 067d5ee9fa..bc11bcec7e 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -27,7 +27,7 @@ import java.lang.reflect.Type internal object MoshiJsonIntegration : JsonIntegration>() { override fun frameworkAdapter( framework: Moshi, - type: Type + type: Type, ): JsonAdapter = framework.adapter(type).nullSafe() override fun listAdapter(elementAdapter: JsonAdapter): JsonAdapter = @@ -36,7 +36,7 @@ internal object MoshiJsonIntegration : JsonIntegration> override fun mapAdapter( framework: Moshi, keyFormatter: JsonFormatter<*>, - valueAdapter: JsonAdapter + valueAdapter: JsonAdapter, ): JsonAdapter = MapJsonAdapter(keyFormatter, valueAdapter).nullSafe() as JsonAdapter override fun structAdapter(framework: Moshi): JsonAdapter = @@ -46,11 +46,11 @@ internal object MoshiJsonIntegration : JsonIntegration> FormatterJsonAdapter(jsonFormatter).nullSafe() as JsonAdapter private class FormatterJsonAdapter( - private val formatter: JsonFormatter + private val formatter: JsonFormatter, ) : JsonAdapter() { override fun toJson( writer: JsonWriter, - value: T? + value: T?, ) { val stringOrNumber = formatter.toStringOrNumber(value!!) if (stringOrNumber is Number) { @@ -72,7 +72,7 @@ internal object MoshiJsonIntegration : JsonIntegration> /** Adapt a list of values by delegating to an adapter for a single value. */ private class ListJsonAdapter( - private val single: JsonAdapter + private val single: JsonAdapter, ) : JsonAdapter>() { override fun fromJson(reader: JsonReader): List { val result = mutableListOf() @@ -86,7 +86,7 @@ internal object MoshiJsonIntegration : JsonIntegration> override fun toJson( writer: JsonWriter, - value: List? + value: List?, ) { writer.beginArray() for (v in value!!) { @@ -99,7 +99,7 @@ internal object MoshiJsonIntegration : JsonIntegration> /** Adapt a list of values by delegating to an adapter for a single value. */ private class MapJsonAdapter( private val keyFormatter: JsonFormatter, - private val valueAdapter: JsonAdapter + private val valueAdapter: JsonAdapter, ) : JsonAdapter>() { override fun fromJson(reader: JsonReader): Map? { val result = mutableMapOf() diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt index 94daa58eca..d3e2cce6f3 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt index 2afb0a65fe..45daf01746 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt @@ -1,11 +1,11 @@ /* - * Copyright 2018 Square Inc. + * Copyright (C) 2018 Square, Inc. * * 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 + * https://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, @@ -53,7 +53,7 @@ class WireJsonAdapterFactory @JvmOverloads constructor( val newMap = typeUrlToAdapter.toMutableMap() for (adapter in adapters) { val key = adapter.typeUrl ?: throw IllegalArgumentException( - "recompile ${adapter.type} to use it with WireJsonAdapterFactory" + "recompile ${adapter.type} to use it with WireJsonAdapterFactory", ) newMap[key] = adapter } @@ -71,7 +71,7 @@ class WireJsonAdapterFactory @JvmOverloads constructor( override fun create( type: Type, annotations: Set, - moshi: Moshi + moshi: Moshi, ): JsonAdapter<*>? { val rawType = Types.getRawType(type) @@ -86,7 +86,7 @@ class WireJsonAdapterFactory @JvmOverloads constructor( ) val jsonAdapters = MoshiJsonIntegration.jsonAdapters(messageAdapter, moshi) val redactedFieldsAdapter = moshi.adapter>( - Types.newParameterizedType(List::class.java, String::class.java) + Types.newParameterizedType(List::class.java, String::class.java), ) MessageJsonAdapter(messageAdapter, jsonAdapters, redactedFieldsAdapter).nullSafe() } diff --git a/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiTest.java b/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiTest.java index 1eb78196cb..438727ad8b 100644 --- a/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiTest.java +++ b/wire-moshi-adapter/src/test/java/com/squareup/wire/MoshiTest.java @@ -1,11 +1,11 @@ /* - * Copyright 2018 Square Inc. + * Copyright (C) 2018 Square, Inc. * * 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 + * https://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, @@ -15,6 +15,8 @@ */ package com.squareup.wire; +import static org.assertj.core.api.Assertions.assertThat; + import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import com.squareup.wire.json.JsonUtils; @@ -31,8 +33,6 @@ import squareup.proto2.keywords.KeywordKotlin; import squareup.proto2.keywords.KeywordKotlin.KeywordKotlinEnum; -import static org.assertj.core.api.Assertions.assertThat; - public class MoshiTest { private static final String ALL_TYPES_IDENTITY_JSON; @@ -40,10 +40,11 @@ public class MoshiTest { try { ALL_TYPES_IDENTITY_JSON = Okio.buffer( - Okio.source( - new File("../wire-tests/src/commonTest/shared/json", - "all_types_identity_proto2.json")) - ).readUtf8(); + Okio.source( + new File( + "../wire-tests/src/commonTest/shared/json", + "all_types_identity_proto2.json"))) + .readUtf8(); } catch (IOException e) { throw new RuntimeException(e); } @@ -87,12 +88,11 @@ private static AllTypes.Builder createIdentityBuilder() { .req_nested_message(new AllTypes.NestedMessage.Builder().a(0).build()); } - private final Moshi moshi = new Moshi.Builder() - .add(new WireJsonAdapterFactory()) - .build(); + private final Moshi moshi = new Moshi.Builder().add(new WireJsonAdapterFactory()).build(); @SuppressWarnings("ConstantConditions") - @Test public void notIdentityOneOf() throws IOException { + @Test + public void notIdentityOneOf() throws IOException { JsonAdapter allTypesAdapter = moshi.adapter(AllTypes.class); AllTypes allTypes = createIdentityBuilder().oneof_int32(0).build(); @@ -100,39 +100,43 @@ private static AllTypes.Builder createIdentityBuilder() { AllTypes parsed = allTypesAdapter.fromJson(ALL_TYPES_IDENTITY_JSON); assertThat(parsed.oneof_int32).isNull(); - String json = ALL_TYPES_IDENTITY_JSON - .substring(0, ALL_TYPES_IDENTITY_JSON.length() - 2) + ",\"oneof_int32\":0}"; + String json = + ALL_TYPES_IDENTITY_JSON.substring(0, ALL_TYPES_IDENTITY_JSON.length() - 2) + + ",\"oneof_int32\":0}"; parsed = allTypesAdapter.fromJson(json); assertThat(parsed.oneof_int32).isEqualTo(0); } @SuppressWarnings("ConstantConditions") - @Test public void nullRepeatedField() throws IOException { - RepeatedPackedAndMap parsed = moshi.adapter(RepeatedPackedAndMap.class) - .fromJson("{\"rep_int32\":null,\"pack_int32\":null,\"map_int32_int32\":null}"); + @Test + public void nullRepeatedField() throws IOException { + RepeatedPackedAndMap parsed = + moshi + .adapter(RepeatedPackedAndMap.class) + .fromJson("{\"rep_int32\":null,\"pack_int32\":null,\"map_int32_int32\":null}"); assertThat(parsed.rep_int32).isEmpty(); assertThat(parsed.pack_int32).isEmpty(); assertThat(parsed.map_int32_int32).isEmpty(); } - @Test public void usedKeywordsInKotlin() throws IOException { + @Test + public void usedKeywordsInKotlin() throws IOException { JsonAdapter adapter = moshi.adapter(KeywordKotlin.class); - KeywordKotlin keyword = new KeywordKotlin.Builder() - .object_("object") - .when_(1) - .enums( - Arrays.asList( - KeywordKotlinEnum.object_, - KeywordKotlinEnum.when_, - KeywordKotlinEnum.fun_, - KeywordKotlinEnum.return_, - KeywordKotlinEnum.open_, - KeywordKotlinEnum.name_, - KeywordKotlinEnum.ordinal_ - ) - ) - .build(); + KeywordKotlin keyword = + new KeywordKotlin.Builder() + .object_("object") + .when_(1) + .enums( + Arrays.asList( + KeywordKotlinEnum.object_, + KeywordKotlinEnum.when_, + KeywordKotlinEnum.fun_, + KeywordKotlinEnum.return_, + KeywordKotlinEnum.open_, + KeywordKotlinEnum.name_, + KeywordKotlinEnum.ordinal_)) + .build(); String json = adapter.toJson(keyword); JsonUtils.assertJsonEquals( "{\"object\":\"object\",\"when\":1, \"fun\":{}, \"return\":[], \"enums\":[\"object\", " @@ -140,27 +144,28 @@ private static AllTypes.Builder createIdentityBuilder() { json); assertThat(adapter.fromJson(json)).isEqualTo(keyword); - String generatedNamedJson = "{\"object_\":\"object\",\"when_\":1, \"fun_\":{}, \"return_\":[], " - + "\"enums\":[\"object_\", \"when_\", \"fun_\", \"return_\", \"open_\", \"name_\", " - + "\"ordinal_\"]}"; + String generatedNamedJson = + "{\"object_\":\"object\",\"when_\":1, \"fun_\":{}, \"return_\":[], " + + "\"enums\":[\"object_\", \"when_\", \"fun_\", \"return_\", \"open_\", \"name_\", " + + "\"ordinal_\"]}"; assertThat(adapter.fromJson(generatedNamedJson)).isEqualTo(keyword); } - @Test public void usedKeywordsInJava() throws IOException { + @Test + public void usedKeywordsInJava() throws IOException { JsonAdapter adapter = moshi.adapter(KeywordJava.class); - KeywordJava keyword = new KeywordJava.Builder() - .public_(true) - .final_("final") - .enums( - Arrays.asList( - KeywordJavaEnum.final_, - KeywordJavaEnum.public_, - KeywordJavaEnum.package_, - KeywordJavaEnum.return_ - ) - ) - .build(); + KeywordJava keyword = + new KeywordJava.Builder() + .public_(true) + .final_("final") + .enums( + Arrays.asList( + KeywordJavaEnum.final_, + KeywordJavaEnum.public_, + KeywordJavaEnum.package_, + KeywordJavaEnum.return_)) + .build(); String json = adapter.toJson(keyword); JsonUtils.assertJsonEquals( "{\"final\":\"final\", \"public\":true, \"package\":{}, \"return\":[], " @@ -168,12 +173,14 @@ private static AllTypes.Builder createIdentityBuilder() { json); assertThat(adapter.fromJson(json)).isEqualTo(keyword); - String generatedNamedJson = "{\"final_\":\"final\", \"public_\":true, \"package_\":{}, " - + "\"return_\":[], \"enums\":[\"final_\", \"public_\", \"package_\", \"return_\"]}"; + String generatedNamedJson = + "{\"final_\":\"final\", \"public_\":true, \"package_\":{}, " + + "\"return_\":[], \"enums\":[\"final_\", \"public_\", \"package_\", \"return_\"]}"; assertThat(adapter.fromJson(generatedNamedJson)).isEqualTo(keyword); } - @Test public void enumKeywordsAtRootInKotlin() throws IOException { + @Test + public void enumKeywordsAtRootInKotlin() throws IOException { JsonAdapter adapter = moshi.adapter(KeywordKotlinEnum.class); KeywordKotlinEnum constant = KeywordKotlinEnum.object_; @@ -185,7 +192,8 @@ private static AllTypes.Builder createIdentityBuilder() { assertThat(adapter.fromJson(generatedNamedJson)).isEqualTo(constant); } - @Test public void enumKeywordsAtRootInJava() throws IOException { + @Test + public void enumKeywordsAtRootInJava() throws IOException { JsonAdapter adapter = moshi.adapter(KeywordJavaEnum.class); KeywordJavaEnum constant = KeywordJavaEnum.final_; diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/DurationRoundTripTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/DurationRoundTripTest.kt index 2f86beb83b..784d3b2439 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/DurationRoundTripTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/DurationRoundTripTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/EmptyRoundTripTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/EmptyRoundTripTest.kt index 6c5556e489..d2c119760e 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/EmptyRoundTripTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/EmptyRoundTripTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -18,9 +18,9 @@ package com.squareup.wire import com.google.protobuf.Empty import org.assertj.core.api.Assertions.assertThat import org.junit.Test -import squareup.proto3.kotlin.alltypes.AllEmptyOuterClass import squareup.proto3.java.alltypes.AllEmpty as AllEmptyJ import squareup.proto3.kotlin.alltypes.AllEmpty as AllEmptyK +import squareup.proto3.kotlin.alltypes.AllEmptyOuterClass class EmptyRoundTripTest { @Test fun empty() { @@ -54,7 +54,7 @@ class EmptyRoundTripTest { empty = Unit, rep_empty = listOf(Unit, Unit), map_int32_empty = mapOf(1 to Unit), - oneof_empty = Unit + oneof_empty = Unit, ) val googleMessageBytes = googleMessage.toByteArray() diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InstantRoundTripTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InstantRoundTripTest.kt index 1ae446ba03..56158e16ad 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InstantRoundTripTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InstantRoundTripTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt index 516103286b..1314bfee65 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropTest.kt index e8cf1c6033..9cc3711bcd 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -19,7 +19,6 @@ import com.google.protobuf.Duration import okio.ByteString import org.junit.Ignore import org.junit.Test -import squareup.proto3.java.interop.InteropTest.InteropWrappers import squareup.proto2.java.interop.InteropBoxOneOf as InteropBoxOneOfJ2 import squareup.proto2.java.interop.InteropCamelCase as InteropCamelCaseJ2 import squareup.proto2.java.interop.InteropDuration as InteropDurationJ2 @@ -43,6 +42,7 @@ import squareup.proto3.java.interop.InteropTest.InteropCamelCase as InteropCamel import squareup.proto3.java.interop.InteropTest.InteropDuration as InteropDurationP3 import squareup.proto3.java.interop.InteropTest.InteropJsonName as InteropJsonNameP3 import squareup.proto3.java.interop.InteropTest.InteropUint64 as InteropUint64P3 +import squareup.proto3.java.interop.InteropTest.InteropWrappers import squareup.proto3.java.interop.InteropUint64 as InteropUint64J3 import squareup.proto3.java.interop.InteropWrappers as InteropWrappersJ3 import squareup.proto3.kotlin.interop.InteropBoxOneOf as InteropBoxOneOfK3 @@ -62,7 +62,7 @@ class InteropTest { Duration.newBuilder() .setSeconds(99L) .setNanos(987_654_321) - .build() + .build(), ) .build(), canonicalJson = """{"value":"99.987654321s"}""", @@ -113,7 +113,7 @@ class InteropTest { .build(), canonicalJson = """{"value":"18446744073709551615"}""", wireAlternateJsons = listOf( - """{"value":"-1"}""" + """{"value":"-1"}""", ), ) max.check(InteropUint64K3(-1L)) @@ -132,7 +132,7 @@ class InteropTest { """{"value":18446744073709551615}""", ), wireAlternateJsons = listOf( - """{"value":"-1"}""" + """{"value":"-1"}""", ), ) max.check(InteropUint64K2(-1L)) @@ -179,7 +179,7 @@ class InteropTest { wireCanonicalJson = """{"hello_world":"1","a__b":"2","_Ccc_ddd":"3","EEee_ff_gGg":"4","a_b_c":"5","GHI":"6","K_L_M":"7","__T__U__V__":"8","_x_y_z_":"9"}""", alternateJsons = listOf( """{"helloWorld":"1","aB":"2","CccDdd":"3","EEeeFfGGg":"4","aBC":"5","GHI":"6","KLM":"7","TUV":"8","XYZ":"9"}""", - ) + ), ) checker.check(InteropCamelCaseK2("1", "2", "3", "4", "5", "6", "7", "8", "9")) @@ -260,17 +260,18 @@ class InteropTest { checker.check( InteropBoxOneOfK2.Builder() .option(OneOf(InteropBoxOneOfK2.OPTION_A, "Hello")) - .build() + .build(), ) checker.check( InteropBoxOneOfK3.Builder() .option(OneOf(InteropBoxOneOfK3.OPTION_A, "Hello")) - .build() + .build(), ) } @Ignore("Needs to implement boxed oneofs in Java.") - @Test fun boxOneOfsJava() { + @Test + fun boxOneOfsJava() { val checker = InteropChecker( protocMessage = InteropBoxOneOfP3.newBuilder() .setA("Hello") @@ -307,7 +308,7 @@ class InteropTest { .bool_value(false) .string_value("") .bytes_value(ByteString.EMPTY) - .build() + .build(), ) checker.check( InteropWrappersK3.Builder() @@ -320,7 +321,7 @@ class InteropTest { .bool_value(false) .string_value("") .bytes_value(ByteString.EMPTY) - .build() + .build(), ) } @@ -359,7 +360,7 @@ class InteropTest { .bool_value(true) .string_value("string") .bytes_value(ByteString.of(1)) - .build() + .build(), ) checker.check( InteropWrappersK3.Builder() @@ -372,7 +373,7 @@ class InteropTest { .bool_value(true) .string_value("string") .bytes_value(ByteString.of(1)) - .build() + .build(), ) } } diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt index ed7610ec45..c3921d04ab 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -66,12 +66,12 @@ class Proto2WireProtocCompatibilityTests { no_default_nested_enum = SimpleMessageK.NestedEnum.BAR, repeated_double = listOf(1.0, 33.0), required_int32 = 46, - other = "hello" + other = "hello", ) val googleMessage = SimpleMessageOuterClass.SimpleMessage.newBuilder() .setOptionalNestedMsg( - SimpleMessageOuterClass.SimpleMessage.NestedMessage.newBuilder().setBb(806).build() + SimpleMessageOuterClass.SimpleMessage.NestedMessage.newBuilder().setBb(806).build(), ) .setNoDefaultNestedEnum(SimpleMessageOuterClass.SimpleMessage.NestedEnum.BAR) .addAllRepeatedDouble(listOf(1.0, 33.0)) @@ -172,7 +172,7 @@ class Proto2WireProtocCompatibilityTests { quilt = Quilt( fringe = listOf(QuiltColor.GREEN), cozy = true, - ) + ), ) // A sample value encoded by ts-proto. @@ -183,7 +183,7 @@ class Proto2WireProtocCompatibilityTests { RepeatedEnum.Quilt.newBuilder() .addAllFringe(listOf(RepeatedEnum.QuiltColor.GREEN)) .setCozy(true) - .build() + .build(), ).build() val wireMessageDecodedFromGoogleMessage = @@ -286,7 +286,7 @@ class Proto2WireProtocCompatibilityTests { oneof_int32 = 0, ext_opt_bool = true, ext_rep_bool = list(true), - ext_pack_bool = list(true) + ext_pack_bool = list(true), ) private val defaultAllTypesProtoc = AllTypesOuterClass.AllTypes.newBuilder() @@ -307,7 +307,7 @@ class Proto2WireProtocCompatibilityTests { .setOptBytes(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())) .setOptNestedEnum(AllTypesOuterClass.AllTypes.NestedEnum.A) .setOptNestedMessage( - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build() + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build(), ) .setReqInt32(111) .setReqUint32(112) @@ -326,7 +326,7 @@ class Proto2WireProtocCompatibilityTests { .setReqBytes(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())) .setReqNestedEnum(AllTypesOuterClass.AllTypes.NestedEnum.A) .setReqNestedMessage( - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build() + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build(), ) .addAllRepInt32(list(111)) .addAllRepUint32(list(112)) @@ -343,13 +343,13 @@ class Proto2WireProtocCompatibilityTests { .addAllRepDouble(list(123.0)) .addAllRepString(list("124")) .addAllRepBytes( - list(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())) + list(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())), ) .addAllRepNestedEnum(list(AllTypesOuterClass.AllTypes.NestedEnum.A)) .addAllRepNestedMessage( list( - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build() - ) + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build(), + ), ) .addAllPackInt32(list(111)) .addAllPackUint32(list(112)) @@ -369,7 +369,7 @@ class Proto2WireProtocCompatibilityTests { .putMapStringString("key", "value") .putMapStringMessage( "message", - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(1).build() + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(1).build(), ) .putMapStringEnum("enum", AllTypesOuterClass.AllTypes.NestedEnum.A) .setOneofInt32(0) @@ -432,7 +432,7 @@ class Proto2WireProtocCompatibilityTests { map_string_enum = mapOf("" to AllTypesK.NestedEnum.UNKNOWN), ext_opt_bool = false, ext_rep_bool = list(false), - ext_pack_bool = list(false) + ext_pack_bool = list(false), ) private val identityAllTypesProtoc = AllTypesOuterClass.AllTypes.newBuilder() @@ -519,7 +519,7 @@ class Proto2WireProtocCompatibilityTests { .setExtension(extRepProto2Enum, list(EnumProto2.A)) .setExtension( extRepProto2Message, - list(MessageProto2.newBuilder().setA(3).setB("Dwyane").build()) + list(MessageProto2.newBuilder().setA(3).setB("Dwyane").build()), ) .setExtension(extRepProto3Enum, list(EnumProto3.A)) .setExtension(extRepProto3Message, list(MessageProto3.newBuilder().setA(1).build())) @@ -552,7 +552,7 @@ class Proto2WireProtocCompatibilityTests { ext_rep_proto2_message = list(MessageProto2K(3, "Dwyane")), ext_rep_proto3_enum = list(EnumProto3K.A), ext_rep_proto3_message = list(MessageProto3K(1)), - oneof_proto3_enum = EnumProto3K.A + oneof_proto3_enum = EnumProto3K.A, ) private val interopWireJ = InteropMessageJ.Builder() diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt index dbe9f10e39..6aca5ddf4a 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -27,29 +27,17 @@ import com.google.protobuf.Timestamp import com.google.protobuf.Value import com.google.protobuf.util.JsonFormat import com.squareup.wire.json.assertJsonEquals +import com.squareup.wire.proto3.kotlin.requiredextension.RequiredExtension as RequiredExtensionK +import com.squareup.wire.proto3.kotlin.requiredextension.RequiredExtensionMessage as RequiredExtensionMessageK +import java.io.File import okio.ByteString import okio.buffer import okio.source import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test -import squareup.proto2.kotlin.interop.type.InteropTypes.MessageProto2 -import squareup.proto3.kotlin.MapTypesOuterClass -import squareup.proto3.kotlin.alltypes.All32OuterClass -import squareup.proto3.kotlin.alltypes.All64OuterClass -import squareup.proto3.kotlin.alltypes.AllTypesOuterClass -import squareup.proto3.kotlin.alltypes.AllWrappersOuterClass -import squareup.proto3.kotlin.alltypes.CamelCaseOuterClass -import squareup.proto3.kotlin.extensions.WireMessageOuterClass -import squareup.proto3.kotlin.interop.InteropMessageOuterClass -import squareup.proto3.kotlin.interop.type.InteropTypes.EnumProto3 -import squareup.proto3.kotlin.interop.type.InteropTypes.MessageProto3 -import squareup.proto3.kotlin.pizza.PizzaOuterClass -import squareup.proto3.wire.extensions.WireMessage -import java.io.File -import com.squareup.wire.proto3.kotlin.requiredextension.RequiredExtension as RequiredExtensionK -import com.squareup.wire.proto3.kotlin.requiredextension.RequiredExtensionMessage as RequiredExtensionMessageK import squareup.proto2.java.interop.type.MessageProto2 as MessageProto2J +import squareup.proto2.kotlin.interop.type.InteropTypes.MessageProto2 import squareup.proto2.kotlin.interop.type.MessageProto2 as MessageProto2K import squareup.proto3.java.alltypes.AllTypes as AllTypesJ import squareup.proto3.java.alltypes.AllWrappers as AllWrappersJ @@ -57,12 +45,24 @@ import squareup.proto3.java.interop.InteropMessage as InteropMessageJ import squareup.proto3.java.interop.type.EnumProto3 as EnumProto3J import squareup.proto3.java.interop.type.MessageProto3 as MessageProto3J import squareup.proto3.kotlin.MapTypes as MapTypesK +import squareup.proto3.kotlin.MapTypesOuterClass +import squareup.proto3.kotlin.alltypes.All32OuterClass +import squareup.proto3.kotlin.alltypes.All64OuterClass import squareup.proto3.kotlin.alltypes.AllTypes as AllTypesK +import squareup.proto3.kotlin.alltypes.AllTypesOuterClass import squareup.proto3.kotlin.alltypes.AllWrappers as AllWrappersK +import squareup.proto3.kotlin.alltypes.AllWrappersOuterClass +import squareup.proto3.kotlin.alltypes.CamelCaseOuterClass +import squareup.proto3.kotlin.extensions.WireMessageOuterClass import squareup.proto3.kotlin.interop.InteropMessage as InteropMessageK +import squareup.proto3.kotlin.interop.InteropMessageOuterClass import squareup.proto3.kotlin.interop.type.EnumProto3 as EnumProto3K +import squareup.proto3.kotlin.interop.type.InteropTypes.EnumProto3 +import squareup.proto3.kotlin.interop.type.InteropTypes.MessageProto3 import squareup.proto3.kotlin.interop.type.MessageProto3 as MessageProto3K import squareup.proto3.kotlin.pizza.PizzaDelivery as PizzaDeliveryK +import squareup.proto3.kotlin.pizza.PizzaOuterClass +import squareup.proto3.wire.extensions.WireMessage class Proto3WireProtocCompatibilityTests { // Note: this test mostly make sure we compile required extension without failing. @@ -88,26 +88,26 @@ class Proto3WireProtocCompatibilityTests { Duration.newBuilder() .setSeconds(1_799) .setNanos(500_000_000) - .build() + .build(), ) .addPizzas( PizzaOuterClass.Pizza.newBuilder() .addToppings("pineapple") .addToppings("onion") - .build() + .build(), ) .setPromotion( Any.pack( PizzaOuterClass.BuyOneGetOnePromotion.newBuilder() .setCoupon("MAUI") - .build() - ) + .build(), + ), ) .setOrderedAt( Timestamp.newBuilder() .setSeconds(-631152000L) // 1950-01-01T00:00:00.250Z. .setNanos(250_000_000) - .build() + .build(), ) .setLoyalty(emptyMap().toStruct()) .build() @@ -120,7 +120,7 @@ class Proto3WireProtocCompatibilityTests { // The shared proto schema don't have the same package. val json = PIZZA_DELIVERY_JSON.replace( "type.googleapis.com/squareup.proto3.BuyOneGetOnePromotion", - "type.googleapis.com/squareup.proto3.kotlin.pizza.BuyOneGetOnePromotion" + "type.googleapis.com/squareup.proto3.kotlin.pizza.BuyOneGetOnePromotion", ) val jsonPrinter = JsonFormat.printer() @@ -191,7 +191,7 @@ class Proto3WireProtocCompatibilityTests { val jsonPrinter = JsonFormat.printer() assertJsonEquals( EXPLICIT_IDENTITY_ALL_TYPES_JSON, - jsonPrinter.print(explicitIdentityAllTypesProtoc) + jsonPrinter.print(explicitIdentityAllTypesProtoc), ) } @@ -305,12 +305,12 @@ class Proto3WireProtocCompatibilityTests { Duration.newBuilder() .setSeconds(1_799) .setNanos(500_000_000) - .build() + .build(), ) .build() val wireMessage = PizzaDeliveryK( - delivered_within_or_free = durationOfSeconds(1_799L, 500_000_000L) + delivered_within_or_free = durationOfSeconds(1_799L, 500_000_000L), ) val googleMessageBytes = googleMessage.toByteArray() @@ -324,12 +324,12 @@ class Proto3WireProtocCompatibilityTests { Timestamp.newBuilder() .setSeconds(-631152000000L) // 1950-01-01T00:00:00.250Z. .setNanos(250_000_000) - .build() + .build(), ) .build() val wireMessage = PizzaDeliveryK( - ordered_at = ofEpochSecond(-631152000000L, 250_000_000L) + ordered_at = ofEpochSecond(-631152000000L, 250_000_000L), ) val googleMessageBytes = googleMessage.toByteArray() @@ -348,16 +348,16 @@ class Proto3WireProtocCompatibilityTests { ListValue.newBuilder() .addValues(Value.newBuilder().setStringValue("Benoît").build()) .addValues(Value.newBuilder().setStringValue("Jesse").build()) - .build() + .build(), ) - .build() + .build(), ) - .build() + .build(), ) .build() val wireMessage = PizzaDeliveryK( - loyalty = mapOf("stamps" to 5.0, "members" to listOf("Benoît", "Jesse")) + loyalty = mapOf("stamps" to 5.0, "members" to listOf("Benoît", "Jesse")), ) val googleMessageBytes = googleMessage.toByteArray() @@ -470,62 +470,62 @@ class Proto3WireProtocCompatibilityTests { .putAllMapInt32Int32( mapOf( Int.MIN_VALUE to Int.MIN_VALUE + 1, - Int.MAX_VALUE to Int.MAX_VALUE - 1 - ) + Int.MAX_VALUE to Int.MAX_VALUE - 1, + ), ) .putAllMapSint32Sint32( mapOf( Int.MIN_VALUE to Int.MIN_VALUE + 1, - Int.MAX_VALUE to Int.MAX_VALUE - 1 - ) + Int.MAX_VALUE to Int.MAX_VALUE - 1, + ), ) .putAllMapSfixed32Sfixed32( mapOf( Int.MIN_VALUE to Int.MIN_VALUE + 1, - Int.MAX_VALUE to Int.MAX_VALUE - 1 - ) + Int.MAX_VALUE to Int.MAX_VALUE - 1, + ), ) .putAllMapFixed32Fixed32( mapOf( Int.MIN_VALUE to Int.MIN_VALUE + 1, - Int.MAX_VALUE to Int.MAX_VALUE - 1 - ) + Int.MAX_VALUE to Int.MAX_VALUE - 1, + ), ) .putAllMapUint32Uint32( mapOf( Int.MIN_VALUE to Int.MIN_VALUE + 1, - Int.MAX_VALUE to Int.MAX_VALUE - 1 - ) + Int.MAX_VALUE to Int.MAX_VALUE - 1, + ), ) .putAllMapInt64Int64( mapOf( Long.MIN_VALUE to Long.MIN_VALUE + 1L, - Long.MAX_VALUE to Long.MAX_VALUE - 1L - ) + Long.MAX_VALUE to Long.MAX_VALUE - 1L, + ), ) .putAllMapSfixed64Sfixed64( mapOf( Long.MIN_VALUE to Long.MIN_VALUE + 1L, - Long.MAX_VALUE to Long.MAX_VALUE - 1L - ) + Long.MAX_VALUE to Long.MAX_VALUE - 1L, + ), ) .putAllMapSint64Sint64( mapOf( Long.MIN_VALUE to Long.MIN_VALUE + 1L, - Long.MAX_VALUE to Long.MAX_VALUE - 1L - ) + Long.MAX_VALUE to Long.MAX_VALUE - 1L, + ), ) .putAllMapFixed64Fixed64( mapOf( Long.MIN_VALUE to Long.MIN_VALUE + 1L, - Long.MAX_VALUE to Long.MAX_VALUE - 1L - ) + Long.MAX_VALUE to Long.MAX_VALUE - 1L, + ), ) .putAllMapUint64Uint64( mapOf( Long.MIN_VALUE to Long.MIN_VALUE + 1L, - Long.MAX_VALUE to Long.MAX_VALUE - 1L - ) + Long.MAX_VALUE to Long.MAX_VALUE - 1L, + ), ) .build() @@ -688,13 +688,13 @@ class Proto3WireProtocCompatibilityTests { .addAllRepDouble(list(123.0)) .addAllRepString(list("124")) .addAllRepBytes( - list(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())) + list(com.google.protobuf.ByteString.copyFrom(ByteString.of(123, 125).toByteArray())), ) .addAllRepNestedEnum(list(AllTypesOuterClass.AllTypes.NestedEnum.A)) .addAllRepNestedMessage( list( - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build() - ) + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(999).build(), + ), ) .addAllPackInt32(list(111)) .addAllPackUint32(list(112)) @@ -714,7 +714,7 @@ class Proto3WireProtocCompatibilityTests { .putMapStringString("key", "value") .putMapStringMessage( "message", - AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(1).build() + AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().setA(1).build(), ) .putMapStringEnum("enum", AllTypesOuterClass.AllTypes.NestedEnum.A) .setOneofInt32(0) @@ -788,7 +788,7 @@ class Proto3WireProtocCompatibilityTests { map_string_string = mapOf("key" to "value"), map_string_message = mapOf("message" to AllTypesK.NestedMessage(1)), map_string_enum = mapOf("enum" to AllTypesK.NestedEnum.A), - oneof_int32 = 0 + oneof_int32 = 0, ) private val defaultAllTypesWireJava = AllTypesJ.Builder() @@ -919,7 +919,7 @@ class Proto3WireProtocCompatibilityTests { map_int32_uint32_value = mapOf(23 to -1), map_int32_bool_value = mapOf(23 to true), map_int32_string_value = mapOf(23 to "Bo knows wrappers"), - map_int32_bytes_value = mapOf(23 to ByteString.of(123, 125)) + map_int32_bytes_value = mapOf(23 to ByteString.of(123, 125)), ) private val defaultAllWrappersWireJava = AllWrappersJ.Builder() @@ -1028,7 +1028,7 @@ class Proto3WireProtocCompatibilityTests { map_int32_int32 = mapOf(0 to 0), map_string_message = mapOf("" to AllTypesK.NestedMessage()), map_string_enum = mapOf("" to AllTypesK.NestedEnum.UNKNOWN), - oneof_int32 = 0 + oneof_int32 = 0, ) private val explicitIdentityAllTypesWireJava = AllTypesJ.Builder() @@ -1119,7 +1119,7 @@ class Proto3WireProtocCompatibilityTests { .addAllRepDouble(emptyList()) .addAllRepString(list("")) .addAllRepBytes( - list(com.google.protobuf.ByteString.copyFrom(ByteString.EMPTY.toByteArray())) + list(com.google.protobuf.ByteString.copyFrom(ByteString.EMPTY.toByteArray())), ) .addAllRepNestedEnum(emptyList()) .addAllRepNestedMessage(emptyList()) @@ -1138,8 +1138,8 @@ class Proto3WireProtocCompatibilityTests { .addAllPackDouble(list(0.0)) .addAllPackNestedEnum( list( - AllTypesOuterClass.AllTypes.NestedEnum.UNKNOWN - ) + AllTypesOuterClass.AllTypes.NestedEnum.UNKNOWN, + ), ) .putMapInt32Int32(0, 0) .putMapStringMessage("", AllTypesOuterClass.AllTypes.NestedMessage.newBuilder().build()) @@ -1172,7 +1172,7 @@ class Proto3WireProtocCompatibilityTests { map_string_proto2_message = mapOf("one" to MessageProto2K(23, "MJ")), map_string_proto3_enum = mapOf("two" to EnumProto3K.A), map_string_proto3_message = mapOf("three" to MessageProto3K(b = "three")), - oneof_proto3_message = MessageProto3K() + oneof_proto3_message = MessageProto3K(), ) private val interopWireJ = InteropMessageJ.Builder() diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt index f2d8c754ed..dfb13e18d3 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt index 93cbdf3f4a..2e423d017d 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/SchemaEncoderInteropTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/SchemaEncoderInteropTest.kt index 22da96e9a4..1f1de1c488 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/SchemaEncoderInteropTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/SchemaEncoderInteropTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -46,42 +46,42 @@ class SchemaEncoderInteropTest { @Test fun `proto2 interop_test`() { checkFileSchemasMatch( wireProtoFile = schema.protoFile("squareup/proto2/kotlin/interop/interop_test.proto")!!, - protocProtoFile = InteropTestP2.getDescriptor().toProto() + protocProtoFile = InteropTestP2.getDescriptor().toProto(), ) } @Test fun `proto3 interop_types`() { checkFileSchemasMatch( wireProtoFile = schema.protoFile("squareup/proto3/kotlin/interop/type/interop_types.proto")!!, - protocProtoFile = InteropTypesP2.getDescriptor().toProto() + protocProtoFile = InteropTypesP2.getDescriptor().toProto(), ) } @Test fun `proto2 interop_service`() { checkFileSchemasMatch( wireProtoFile = schema.protoFile("squareup/proto2/kotlin/interop/interop_service.proto")!!, - protocProtoFile = InteropServiceOuterClassP2.getDescriptor().toProto() + protocProtoFile = InteropServiceOuterClassP2.getDescriptor().toProto(), ) } @Test fun `proto2 all_types`() { checkFileSchemasMatch( wireProtoFile = schema.protoFile("squareup/proto2/kotlin/alltypes/all_types.proto")!!, - protocProtoFile = AllTypesOuterClassP2.getDescriptor().toProto() + protocProtoFile = AllTypesOuterClassP2.getDescriptor().toProto(), ) } @Test fun `proto3 all_types`() { checkFileSchemasMatch( wireProtoFile = schema.protoFile("squareup/proto3/kotlin/alltypes/all_types_test_proto3_optional.proto")!!, - protocProtoFile = AllTypesOuterClassP3.getDescriptor().toProto() + protocProtoFile = AllTypesOuterClassP3.getDescriptor().toProto(), ) } @Test fun `proto2 all_options`() { checkFileSchemaOptionsMatch( wireProtoFile = schema.protoFile("squareup/proto2/kotlin/alloptions/all_options.proto")!!, - protocProtoFile = AllOptionsP2.getDescriptor().toProto() + protocProtoFile = AllOptionsP2.getDescriptor().toProto(), ) } @@ -91,7 +91,7 @@ class SchemaEncoderInteropTest { */ private fun checkFileSchemasMatch( wireProtoFile: ProtoFile, - protocProtoFile: FileDescriptorProto + protocProtoFile: FileDescriptorProto, ) { val wireBytes = SchemaEncoder(schema).encode(wireProtoFile) val wireDescriptor = FileDescriptorProto.parseFrom(wireBytes.toByteArray(), extensionRegistry) @@ -107,7 +107,7 @@ class SchemaEncoderInteropTest { */ private fun checkFileSchemaOptionsMatch( wireProtoFile: ProtoFile, - protocProtoFile: FileDescriptorProto + protocProtoFile: FileDescriptorProto, ) { val wireBytes = SchemaEncoder(schema).encode(wireProtoFile) val wireDescriptor = FileDescriptorProto.parseFrom(wireBytes.toByteArray(), extensionRegistry) diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt index 2e593860e4..37413f71b8 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -21,9 +21,9 @@ import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.entry import org.junit.Assert.fail import org.junit.Test -import squareup.proto3.kotlin.alltypes.AllStructsOuterClass import squareup.proto3.java.alltypes.AllStructs as AllStructsJ import squareup.proto3.kotlin.alltypes.AllStructs as AllStructsK +import squareup.proto3.kotlin.alltypes.AllStructsOuterClass class StructTest { @Test fun nullValue() { @@ -52,7 +52,7 @@ class StructTest { -0.0, 0.0, Double.POSITIVE_INFINITY, - Double.NaN + Double.NaN, ).toListValue() val wireMessage = listOf( @@ -60,7 +60,7 @@ class StructTest { -0.0, 0.0, Double.POSITIVE_INFINITY, - Double.NaN + Double.NaN, ) val googleMessageBytes = googleMessage.toByteArray() @@ -135,7 +135,7 @@ class StructTest { "c" to true, "d" to "cash", "e" to listOf("g", "h"), - "f" to mapOf("i" to "j", "k" to "l") + "f" to mapOf("i" to "j", "k" to "l"), ).toStruct() val wireMessage = mapOf( @@ -144,7 +144,7 @@ class StructTest { "c" to true, "d" to "cash", "e" to listOf("g", "h"), - "f" to mapOf("i" to "j", "k" to "l") + "f" to mapOf("i" to "j", "k" to "l"), ) val googleMessageBytes = googleMessage.toByteArray() @@ -224,7 +224,7 @@ class StructTest { true, "cash", listOf("a", "b"), - mapOf("c" to "d", "e" to "f") + mapOf("c" to "d", "e" to "f"), ).toListValue() val wireMessage = listOf( @@ -233,7 +233,7 @@ class StructTest { true, "cash", listOf("a", "b"), - mapOf("c" to "d", "e" to "f") + mapOf("c" to "d", "e" to "f"), ) val googleMessageBytes = googleMessage.toByteArray() @@ -296,7 +296,7 @@ class StructTest { .build() val wireAllStructKotlin = AllStructsK( struct = emptyMap(), - list = emptyList() + list = emptyList(), ) val protocAllStructBytes = protocAllStruct.toByteArray() @@ -336,7 +336,7 @@ class StructTest { value_b = 33.0, value_c = true, value_e = mapOf("a" to 1.0), - value_f = listOf("a", 3.0) + value_f = listOf("a", 3.0), ) val protocAllStructBytes = protocAllStruct.toByteArray() @@ -388,7 +388,7 @@ class StructTest { "c" to "j", "d" to 5.0, "e" to false, - "f" to null + "f" to null, ) val allStructs = AllStructsJ.Builder() @@ -407,7 +407,7 @@ class StructTest { entry("c", "j"), entry("d", 5.0), entry("e", false), - entry("f", null) + entry("f", null), ) } @@ -418,7 +418,7 @@ class StructTest { "c" to "j", "d" to 5.0, "e" to false, - "f" to null + "f" to null, ) val allStructs = AllStructsK.Builder() @@ -437,7 +437,7 @@ class StructTest { entry("c", "j"), entry("d", 5.0), entry("e", false), - entry("f", null) + entry("f", null), ) } @@ -449,7 +449,7 @@ class StructTest { } catch (e: IllegalArgumentException) { assertThat(e).hasMessage( "struct value struct must be a JSON type " + - "(null, Boolean, Double, String, List, or Map) but was class kotlin.Int: 1" + "(null, Boolean, Double, String, List, or Map) but was class kotlin.Int: 1", ) } } diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt index 757b3f94c4..ed21574ef5 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -20,7 +20,7 @@ import com.google.protobuf.DescriptorProtos.FieldDescriptorProto import com.google.protobuf.DescriptorProtos.FileDescriptorProto class UnwantedValueStripper( - val clearJsonName: Boolean = false + val clearJsonName: Boolean = false, ) { /** diff --git a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt index 28d9cf9a68..8114c5126e 100644 --- a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt +++ b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, diff --git a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/WireTestLogger.kt b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/WireTestLogger.kt index 7e619679b2..e30dd60f74 100644 --- a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/WireTestLogger.kt +++ b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/WireTestLogger.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt deleted file mode 100644 index b1e145495d..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire - -import com.squareup.wire.schema.Location -import com.squareup.wire.schema.SchemaException -import okio.Path.Companion.toPath -import org.assertj.core.api.Assertions.assertThat -import kotlin.test.Test -import kotlin.test.assertFailsWith - -class SchemaBuilderTest { - @Test fun emptySchema() { - val exception = assertFailsWith { - buildSchema {} - } - assertThat(exception.message).isEqualTo("no sources") - } - - @Test fun sourcePathOnly() { - val schema = buildSchema { - add( - "example1.proto".toPath(), - """ - |syntax = "proto2"; - | - |message A { - | optional B b = 1; - |} - |message B { - | optional C c = 1; - |} - |message C { - |} - |""".trimMargin() - ) - add( - "example2.proto".toPath(), - """ - |syntax = "proto2"; - | - |message D { - |} - |""".trimMargin() - ) - } - assertThat(schema.protoFiles.map { it.location }).containsExactlyInAnyOrder( - Location.get("/sourcePath", "example1.proto"), - Location.get("/sourcePath", "example2.proto"), - Location.get("google/protobuf/descriptor.proto"), - Location.get("wire/extensions.proto"), - ) - } -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt deleted file mode 100644 index b9d4ef6315..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire.recipes - -import com.squareup.wire.schema.Extend -import com.squareup.wire.schema.Field -import com.squareup.wire.schema.MessageType -import com.squareup.wire.schema.SchemaHandler -import com.squareup.wire.schema.Service -import com.squareup.wire.schema.Type -import okio.Path - -/** Sample schema validator that enforces a field naming pattern. */ -class ErrorReportingSchemaHandler : SchemaHandler() { - override fun handle(type: Type, context: SchemaHandler.Context): Path? { - val errorCollector = context.errorCollector - - if ("descriptor.proto" in type.location.path) return null // Don't report errors on built-in stuff. - if (type is MessageType) { - for (field in type.fields) { - if (field.name.startsWith("a")) { - errorCollector.at(field) += "field starts with 'a'" - } - } - } - return null - } - - override fun handle(service: Service, context: SchemaHandler.Context): List = emptyList() - - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = null -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt deleted file mode 100644 index 831789977b..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire.recipes - -import com.squareup.wire.WireTestLogger -import com.squareup.wire.buildSchema -import com.squareup.wire.schema.ErrorCollector -import com.squareup.wire.schema.SchemaException -import com.squareup.wire.schema.SchemaHandler -import okio.Path.Companion.toPath -import okio.fakefilesystem.FakeFileSystem -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test -import kotlin.test.assertFailsWith - -class ErrorReportingSchemaHandlerTest { - @Test fun errorsWhenStartsWithA() { - val schema = buildSchema { - add( - name = "a.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |message A { - | optional string acrobatic = 1; - | optional string biofidus = 2; - |} - """.trimMargin() - ) - add( - name = "b.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |message B { - | optional string comment = 1; - | optional string dinosaur = 2; - |} - """.trimMargin() - ) - } - - val errorCollector = ErrorCollector() - val context = SchemaHandler.Context( - fileSystem = FakeFileSystem(), - outDirectory = "out".toPath(), - logger = WireTestLogger(), - errorCollector = errorCollector, - ) - - ErrorReportingSchemaHandler().handle(schema, context) - val exception = assertFailsWith { - errorCollector.throwIfNonEmpty() - } - - assertThat(exception.message).startsWith("field starts with 'a'") - } -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt deleted file mode 100644 index e2601b239f..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire.recipes - -import com.squareup.wire.schema.Extend -import com.squareup.wire.schema.Field -import com.squareup.wire.schema.SchemaHandler -import com.squareup.wire.schema.Service -import com.squareup.wire.schema.Type -import okio.Path -import okio.Path.Companion.toPath -import okio.buffer - -/** Sample schema handler which writes to disk generated artifacts. */ -class LogToFileHandler : SchemaHandler() { - private val filePath = "log.txt".toPath() - - override fun handle(type: Type, context: SchemaHandler.Context): Path? { - context.fileSystem.appendingSink(filePath).buffer().use { - it.writeUtf8("Generating type: ${type.type}\n") - } - - return null - } - - override fun handle(service: Service, context: SchemaHandler.Context): List { - context.fileSystem.appendingSink(filePath).buffer().use { - it.writeUtf8("Generating service: ${service.type}\n") - } - - return listOf() - } - - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? { - context.fileSystem.appendingSink(filePath).buffer().use { - it.writeUtf8("Generating ${extend.type} on ${field.location}\n") - } - - return null - } -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt deleted file mode 100644 index 21a3c2de18..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire.recipes - -import com.squareup.wire.WireTestLogger -import com.squareup.wire.buildSchema -import com.squareup.wire.schema.SchemaHandler -import okio.BufferedSource -import okio.Path.Companion.toPath -import okio.fakefilesystem.FakeFileSystem -import org.junit.Test -import kotlin.test.assertEquals - -class LogToFileHandlerTest { - @Test fun loggingTypes() { - val schema = buildSchema { - add( - name = "test/message.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |package test; - | - |message Request {} - |message Response { - | optional string result = 1; - |} - """.trimMargin() - ) - add( - name = "test/service.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |package test; - | - |import "test/message.proto"; - | - |service MyService { - | rpc fetch(test.Request) returns(test.Response) {}; - |} - """.trimMargin() - ) - } - - val context = SchemaHandler.Context( - fileSystem = FakeFileSystem(), - outDirectory = "/".toPath(), - logger = WireTestLogger(), - sourcePathPaths = setOf("test/message.proto", "test/service.proto"), - ) - LogToFileHandler().handle(schema, context) - - val content = context.fileSystem.read("log.txt".toPath(), BufferedSource::readUtf8) - val expected = """ - |Generating type: test.Request - |Generating type: test.Response - |Generating service: test.MyService - |""".trimMargin() - assertEquals(expected, content) - } -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt deleted file mode 100644 index ef660abe0a..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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.squareup.wire.recipes - -import com.squareup.wire.schema.Extend -import com.squareup.wire.schema.Field -import com.squareup.wire.schema.SchemaHandler -import com.squareup.wire.schema.Service -import com.squareup.wire.schema.Type -import okio.Path - -/** Sample schema handler which logs handled types and services. */ -class LogToWireLoggerHandler : SchemaHandler() { - override fun handle(type: Type, context: SchemaHandler.Context): Path? { - context.logger.artifactHandled( - context.outDirectory, type.type.enclosingTypeOrPackage ?: "", type.type.simpleName - ) - - return null - } - - override fun handle(service: Service, context: SchemaHandler.Context): List { - context.logger.artifactHandled( - context.outDirectory, service.type.enclosingTypeOrPackage ?: "", service.type.simpleName - ) - - return listOf() - } - - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? { - return null - } -} diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt deleted file mode 100644 index 0bbaea5292..0000000000 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2022 Block Inc. - * - * 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. - */ -@file:Suppress("UsePropertyAccessSyntax") - -package com.squareup.wire.recipes - -import com.squareup.wire.WireTestLogger -import com.squareup.wire.buildSchema -import com.squareup.wire.schema.SchemaHandler -import okio.Path.Companion.toPath -import okio.fakefilesystem.FakeFileSystem -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test - -class LogToWireLoggerHandlerTest { - @Test fun loggingArtifacts() { - val schema = buildSchema { - add( - name = "test/message.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |package test; - | - |message Request {} - |message Response { - | optional string result = 1; - |} - """.trimMargin() - ) - add( - name = "test/service.proto".toPath(), - protoFile = """ - |syntax = "proto2"; - | - |package test; - | - |import "test/message.proto"; - | - |service MyService { - | rpc fetch(test.Request) returns(test.Response) {}; - |} - """.trimMargin() - ) - } - val logger = WireTestLogger() - val context = SchemaHandler.Context( - fileSystem = FakeFileSystem(), - outDirectory = "out".toPath(), - logger = logger, - sourcePathPaths = setOf("test/message.proto", "test/service.proto"), - ) - LogToWireLoggerHandler().handle(schema, context) - - assertThat(logger.artifactHandled.removeFirst()).isEqualTo(Triple("out".toPath(), "test", "Request")) - assertThat(logger.artifactHandled.removeFirst()).isEqualTo(Triple("out".toPath(), "test", "Response")) - assertThat(logger.artifactHandled.removeFirst()).isEqualTo(Triple("out".toPath(), "test", "MyService")) - assertThat(logger.artifactHandled.isEmpty()).isTrue() - } -} diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt index b1e145495d..08f7acc1cd 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/SchemaBuilderTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -17,10 +17,10 @@ package com.squareup.wire import com.squareup.wire.schema.Location import com.squareup.wire.schema.SchemaException -import okio.Path.Companion.toPath -import org.assertj.core.api.Assertions.assertThat import kotlin.test.Test import kotlin.test.assertFailsWith +import okio.Path.Companion.toPath +import org.assertj.core.api.Assertions.assertThat class SchemaBuilderTest { @Test fun emptySchema() { @@ -45,7 +45,8 @@ class SchemaBuilderTest { |} |message C { |} - |""".trimMargin() + | + """.trimMargin(), ) add( "example2.proto".toPath(), @@ -54,7 +55,8 @@ class SchemaBuilderTest { | |message D { |} - |""".trimMargin() + | + """.trimMargin(), ) } assertThat(schema.protoFiles.map { it.location }).containsExactlyInAnyOrder( diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt index b9d4ef6315..75985fca47 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandler.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt index 831789977b..e1fed515a2 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/ErrorReportingSchemaHandlerTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -20,11 +20,11 @@ import com.squareup.wire.buildSchema import com.squareup.wire.schema.ErrorCollector import com.squareup.wire.schema.SchemaException import com.squareup.wire.schema.SchemaHandler +import kotlin.test.assertFailsWith import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem import org.assertj.core.api.Assertions.assertThat import org.junit.Test -import kotlin.test.assertFailsWith class ErrorReportingSchemaHandlerTest { @Test fun errorsWhenStartsWithA() { @@ -38,7 +38,7 @@ class ErrorReportingSchemaHandlerTest { | optional string acrobatic = 1; | optional string biofidus = 2; |} - """.trimMargin() + """.trimMargin(), ) add( name = "b.proto".toPath(), @@ -49,7 +49,7 @@ class ErrorReportingSchemaHandlerTest { | optional string comment = 1; | optional string dinosaur = 2; |} - """.trimMargin() + """.trimMargin(), ) } diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt index e2601b239f..099016c0ac 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandler.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt index 21a3c2de18..5f79546041 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToFileHandlerTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -18,11 +18,11 @@ package com.squareup.wire.recipes import com.squareup.wire.WireTestLogger import com.squareup.wire.buildSchema import com.squareup.wire.schema.SchemaHandler +import kotlin.test.assertEquals import okio.BufferedSource import okio.Path.Companion.toPath import okio.fakefilesystem.FakeFileSystem import org.junit.Test -import kotlin.test.assertEquals class LogToFileHandlerTest { @Test fun loggingTypes() { @@ -38,7 +38,7 @@ class LogToFileHandlerTest { |message Response { | optional string result = 1; |} - """.trimMargin() + """.trimMargin(), ) add( name = "test/service.proto".toPath(), @@ -52,7 +52,7 @@ class LogToFileHandlerTest { |service MyService { | rpc fetch(test.Request) returns(test.Response) {}; |} - """.trimMargin() + """.trimMargin(), ) } @@ -69,7 +69,8 @@ class LogToFileHandlerTest { |Generating type: test.Request |Generating type: test.Response |Generating service: test.MyService - |""".trimMargin() + | + """.trimMargin() assertEquals(expected, content) } } diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt index ef660abe0a..6eb424bd0a 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -26,7 +26,9 @@ import okio.Path class LogToWireLoggerHandler : SchemaHandler() { override fun handle(type: Type, context: SchemaHandler.Context): Path? { context.logger.artifactHandled( - context.outDirectory, type.type.enclosingTypeOrPackage ?: "", type.type.simpleName + context.outDirectory, + type.type.enclosingTypeOrPackage ?: "", + type.type.simpleName, ) return null @@ -34,7 +36,9 @@ class LogToWireLoggerHandler : SchemaHandler() { override fun handle(service: Service, context: SchemaHandler.Context): List { context.logger.artifactHandled( - context.outDirectory, service.type.enclosingTypeOrPackage ?: "", service.type.simpleName + context.outDirectory, + service.type.enclosingTypeOrPackage ?: "", + service.type.simpleName, ) return listOf() diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt index 0bbaea5292..e66251c331 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandlerTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -39,7 +39,7 @@ class LogToWireLoggerHandlerTest { |message Response { | optional string result = 1; |} - """.trimMargin() + """.trimMargin(), ) add( name = "test/service.proto".toPath(), @@ -53,7 +53,7 @@ class LogToWireLoggerHandlerTest { |service MyService { | rpc fetch(test.Request) returns(test.Response) {}; |} - """.trimMargin() + """.trimMargin(), ) } val logger = WireTestLogger() diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt index c82b2a50d6..09656227e1 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -40,7 +40,7 @@ class MarkdownHandler : SchemaHandler() { private fun writeMarkdownFile( protoType: ProtoType, markdown: String, - context: SchemaHandler.Context + context: SchemaHandler.Context, ): Path { val path = context.outDirectory / toPath(protoType).joinToString(separator = "/") context.fileSystem.createDirectories(path.parent!!) @@ -65,7 +65,8 @@ class MarkdownHandler : SchemaHandler() { |# ${type.type.simpleName} | |${type.documentation} - |""".trimMargin() + | + """.trimMargin() } private fun toMarkdown(service: Service): String { @@ -73,6 +74,7 @@ class MarkdownHandler : SchemaHandler() { |# ${service.type.simpleName} | |${service.documentation} - |""".trimMargin() + | + """.trimMargin() } } diff --git a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandlerTest.kt b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandlerTest.kt index cdc9d9ab0f..219dc8d94e 100644 --- a/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandlerTest.kt +++ b/wire-schema-tests/src/jvmTest/kotlin/com/squareup/wire/recipes/MarkdownHandlerTest.kt @@ -1,11 +1,11 @@ /* - * Copyright 2022 Block Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -38,7 +38,7 @@ class MarkdownHandlerTest { |message Red { | optional string oval = 1; |} - """.trimMargin() + """.trimMargin(), ) add( name = "squareup/colors/blue.proto".toPath(), @@ -51,7 +51,7 @@ class MarkdownHandlerTest { | optional string circle = 1; | optional squareup.polygons.Triangle triangle = 2; |} - """.trimMargin() + """.trimMargin(), ) add( name = "squareup/polygons/triangle.proto".toPath(), @@ -66,7 +66,7 @@ class MarkdownHandlerTest { | RIGHTANGLED = 3; | } |} - """.trimMargin() + """.trimMargin(), ) } @@ -82,7 +82,7 @@ class MarkdownHandlerTest { assertThat(fileSystem.findFiles("generated")) .containsRelativePaths( "generated/markdown/squareup/colors/Blue.md", - "generated/markdown/squareup/colors/Red.md" + "generated/markdown/squareup/colors/Red.md", ) assertThat(fileSystem.readUtf8("generated/markdown/squareup/colors/Blue.md")) .isEqualTo( @@ -90,7 +90,8 @@ class MarkdownHandlerTest { |# Blue | |This is the color of the sky. - |""".trimMargin() + | + """.trimMargin(), ) assertThat(fileSystem.readUtf8("generated/markdown/squareup/colors/Red.md")) .isEqualTo( @@ -98,7 +99,8 @@ class MarkdownHandlerTest { |# Red | |This is the color of the sky when the sky is lava. - |""".trimMargin() + | + """.trimMargin(), ) } } diff --git a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/MessageElementTest.kt b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/MessageElementTest.kt index bfa09d2e22..c9921e65ab 100644 --- a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/MessageElementTest.kt +++ b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/MessageElementTest.kt @@ -352,7 +352,7 @@ class MessageElementTest { |message Message { | oneof hi { | string name = 1; - | + | | group Stuff = 3 { | optional int32 result_per_page = 4; | optional int32 page_count = 5; diff --git a/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt b/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt index 1de24252e1..eec9834423 100644 --- a/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt +++ b/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt @@ -1,3 +1,18 @@ +/* + * Copyright (C) 2023 Square, Inc. + * + * 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 + * + * https://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.squareup.wire.swift import com.squareup.wire.Syntax.PROTO_2 @@ -29,7 +44,6 @@ import io.outfoxx.swiftpoet.FileMemberSpec import io.outfoxx.swiftpoet.FileSpec import io.outfoxx.swiftpoet.FunctionSignatureSpec import io.outfoxx.swiftpoet.FunctionSpec -import io.outfoxx.swiftpoet.INT import io.outfoxx.swiftpoet.INT32 import io.outfoxx.swiftpoet.INT64 import io.outfoxx.swiftpoet.Modifier.FILEPRIVATE @@ -55,7 +69,7 @@ import java.util.Locale.US class SwiftGenerator private constructor( val schema: Schema, private val nameToTypeName: Map, - private val referenceCycleIndirections: Map> + private val referenceCycleIndirections: Map>, ) { private val proto2Codable = DeclaredTypeName.typeName("Wire.Proto2Codable") private val proto3Codable = DeclaredTypeName.typeName("Wire.Proto3Codable") @@ -157,7 +171,8 @@ class SwiftGenerator private constructor( get() = when (encodeMode!!) { EncodeMode.MAP -> DICTIONARY.parameterizedBy(keyType.typeName, valueType.typeName) EncodeMode.REPEATED, - EncodeMode.PACKED -> ARRAY.parameterizedBy(type!!.typeName) + EncodeMode.PACKED, + -> ARRAY.parameterizedBy(type!!.typeName) EncodeMode.NULL_IF_ABSENT -> OPTIONAL.parameterizedBy(type!!.typeName) EncodeMode.REQUIRED -> type!!.typeName EncodeMode.OMIT_IDENTITY -> { @@ -222,17 +237,17 @@ class SwiftGenerator private constructor( .fields .mapNotNull { schema.getType(it.type!!) as? EnumType } .forEach { enum -> - // ensure that a 0 case exists - if (enum.constants.filter { it.tag == 0 }.isEmpty()) { - throw NoSuchElementException("Missing a zero value for ${enum.name}") - } + // ensure that a 0 case exists + if (enum.constants.filter { it.tag == 0 }.isEmpty()) { + throw NoSuchElementException("Missing a zero value for ${enum.name}") + } } } @OptIn(ExperimentalStdlibApi::class) // TODO move to build flag private fun generateMessage( type: MessageType, - fileMembers: MutableList + fileMembers: MutableList, ): List { val structType = type.typeName val oneOfEnumNames = type.oneOfs.associateWith { structType.nestedType(it.name.capitalize(US)) } @@ -256,13 +271,13 @@ class SwiftGenerator private constructor( if (type.isHeapAllocated) { addAttribute( - AttributeSpec.builder("dynamicMemberLookup").build() + AttributeSpec.builder("dynamicMemberLookup").build(), ) addProperty( PropertySpec.varBuilder(storageName, storageType, PRIVATE) .addAttribute(AttributeSpec.builder(heap).build()) - .build() + .build(), ) generateMessageStoragePropertyDelegates(type, storageName, storageType) @@ -283,10 +298,10 @@ class SwiftGenerator private constructor( "self.%N = %T(%L)", storageName, storageType, - storageParams.joinToCode(separator = ",%W") + storageParams.joinToCode(separator = ",%W"), ) } - .build() + .build(), ) addFunction( @@ -295,7 +310,7 @@ class SwiftGenerator private constructor( .beginControlFlow("if", "!isKnownUniquelyReferenced(&_%N)", storageName) .addStatement("_%1N = %2T(wrappedValue: %1N)", storageName, heap) .endControlFlow("if") - .build() + .build(), ) } else { generateMessageProperties(type, oneOfEnumNames) @@ -353,7 +368,7 @@ class SwiftGenerator private constructor( } } } - .build() + .build(), ) } else { null @@ -368,7 +383,7 @@ class SwiftGenerator private constructor( generateMessageProperties(type, oneOfEnumNames, forStorageType = true) generateMessageConstructor(type, oneOfEnumNames, includeDefaults = false) } - .build() + .build(), ) .build() fileMembers += FileMemberSpec.builder(storageExtension).build() @@ -381,7 +396,7 @@ class SwiftGenerator private constructor( .addParameter("from", "reader", protoReader) .throws(true) .addStatement("self.%N = try %T(from: reader)", storageName, storageType) - .build() + .build(), ) .addFunction( FunctionSpec.builder("encode") @@ -389,7 +404,7 @@ class SwiftGenerator private constructor( .addParameter("to", "writer", protoWriter) .throws(true) .addStatement("try %N.encode(to: writer)", storageName) - .build() + .build(), ) .build() fileMembers += FileMemberSpec.builder(structProtoCodableExtension).build() @@ -442,9 +457,9 @@ class SwiftGenerator private constructor( .getter( FunctionSpec.getterBuilder() .addStatement("return %N.description", storageName) - .build() + .build(), ) - .build() + .build(), ) val storageRedactableExtension = ExtensionSpec.builder(storageType) @@ -452,7 +467,7 @@ class SwiftGenerator private constructor( .addType( TypeAliasSpec.builder("RedactedKeys", structType.nestedType("RedactedKeys")) .addModifiers(PUBLIC) - .build() + .build(), ) .build() fileMembers += FileMemberSpec.builder(storageRedactableExtension) @@ -490,7 +505,7 @@ class SwiftGenerator private constructor( type: MessageType, structType: DeclaredTypeName, oneOfEnumNames: Map, - propertyNames: Collection + propertyNames: Collection, ): ExtensionSpec.Builder = apply { addSuperType(type.protoCodableType) @@ -507,23 +522,23 @@ class SwiftGenerator private constructor( type.fields.forEach { field -> val localType = when (type.syntax) { PROTO_2 -> if (field.isRepeated || field.isMap) { - field.typeName - } else { - field.typeName.makeOptional() - } + field.typeName + } else { + field.typeName.makeOptional() + } PROTO_3 -> if (field.isOptional || (field.isEnum && !field.isRepeated)) { - field.typeName.makeOptional() - } else { - field.typeName - } + field.typeName.makeOptional() + } else { + field.typeName + } } val initializer = when (type.syntax) { PROTO_2 -> when { - field.isMap -> "[:]" - field.isRepeated -> "[]" - else -> "nil" - } + field.isMap -> "[:]" + field.isRepeated -> "[]" + else -> "nil" + } PROTO_3 -> field.proto3InitialValue } @@ -575,7 +590,7 @@ class SwiftGenerator private constructor( field.tag, oneOf.name, field.name, - field.typeName.makeNonOptional() + field.typeName.makeNonOptional(), ) } else -> { @@ -584,7 +599,7 @@ class SwiftGenerator private constructor( field.tag, oneOf.name, field.name, - field.typeName.makeNonOptional() + field.typeName.makeNonOptional(), ) } } @@ -598,7 +613,7 @@ class SwiftGenerator private constructor( // Check required and bind members. addStatement("") type.fields.forEach { field -> - val initializer = when(type.syntax) { + val initializer = when (type.syntax) { PROTO_2 -> if (field.isOptional || field.isRepeated || field.isMap) { CodeBlock.of("%N", field.name) } else { @@ -616,7 +631,7 @@ class SwiftGenerator private constructor( addStatement("self.%1N = %1N", oneOf.name) } } - .build() + .build(), ) val writer = if ("writer" in propertyNames) "_writer" else "writer" @@ -654,7 +669,7 @@ class SwiftGenerator private constructor( } } .addStatement("try $writer.writeUnknownFields(unknownFields)") - .build() + .build(), ) } @@ -668,7 +683,7 @@ class SwiftGenerator private constructor( .addModifiers(PUBLIC) .addModifiers(STATIC) .addStatement("return \"%N\"", type.type.typeUrl!!) - .build() + .build(), ) } @@ -693,8 +708,8 @@ class SwiftGenerator private constructor( .throws(true) .addStatement("let container = try decoder.singleValueContainer()") .addStatement("self.%N = try container.decode(%T.self)", storageName, storageType) - .build() - ) + .build(), + ) addFunction( FunctionSpec.builder("encode") .addParameter("to", "encoder", encoder) @@ -702,15 +717,15 @@ class SwiftGenerator private constructor( .throws(true) .addStatement("var container = encoder.singleValueContainer()") .addStatement("try container.encode(%N)", storageName) - .build() - ) + .build(), + ) } .build() } private fun messageCodableExtension( type: MessageType, - structType: DeclaredTypeName + structType: DeclaredTypeName, ): ExtensionSpec { return ExtensionSpec.builder(structType) .addSuperType(codable) @@ -730,7 +745,7 @@ class SwiftGenerator private constructor( TypeSpec.enumBuilder(codingKeys) .addModifiers(PUBLIC) .addSuperType(codingKey) - .build() + .build(), ) } @@ -776,7 +791,7 @@ class SwiftGenerator private constructor( addStatement( "self.%1N = try container.$decode($typeArg%2T.self, $forKeys: $keys)", field.name, - typeName + typeName, ) } @@ -799,7 +814,7 @@ class SwiftGenerator private constructor( "let %1N = try container.decodeIfPresent(%2T.self, forKey: %3S)", field.name, typeName, - keyName + keyName, ) } else { nextControlFlow( @@ -807,7 +822,7 @@ class SwiftGenerator private constructor( "let %1N = try container.decodeIfPresent(%2T.self, forKey: %3S)", field.name, typeName, - keyName + keyName, ) } addStatement("self.%1N = .%2N(%2N)", oneOf.name, field.name) @@ -817,7 +832,7 @@ class SwiftGenerator private constructor( endControlFlow("if") } } - .build() + .build(), ) addFunction( FunctionSpec.builder("encode") @@ -854,13 +869,13 @@ class SwiftGenerator private constructor( val (keys, args) = field.codableName?.let { codableName -> Pair( "preferCamelCase ? %2S : %1S", - arrayOf(field.name, codableName) + arrayOf(field.name, codableName), ) } ?: Pair("%1S", arrayOf(field.name)) addStatement( "try container.$encode(${typeArg}self.%1N, forKey: $keys)", - *args + *args, ) } @@ -896,20 +911,20 @@ class SwiftGenerator private constructor( val (keys, args) = field.codableName?.let { codableName -> Pair( "preferCamelCase ? %2S : %1S", - arrayOf(field.name, codableName) + arrayOf(field.name, codableName), ) } ?: Pair("%1S", arrayOf(field.name)) addStatement( "case .%1N(let %1N): try container.encode(%1N, forKey: $keys)", - *args + *args, ) } addStatement("case %T.none: break", OPTIONAL) endControlFlow("switch") } } - .build() + .build(), ) } } @@ -927,7 +942,7 @@ class SwiftGenerator private constructor( private fun FunctionSpec.Builder.addParameters( type: MessageType, oneOfEnumNames: Map, - includeDefaults: Boolean = true + includeDefaults: Boolean = true, ) = apply { type.fields.forEach { field -> addParameter( @@ -937,7 +952,7 @@ class SwiftGenerator private constructor( withFieldDefault(field) } } - .build() + .build(), ) } type.oneOfs.forEach { oneOf -> @@ -945,7 +960,7 @@ class SwiftGenerator private constructor( addParameter( ParameterSpec.builder(oneOf.name, enumName) .defaultValue("nil") - .build() + .build(), ) } } @@ -953,7 +968,7 @@ class SwiftGenerator private constructor( private fun TypeSpec.Builder.generateMessageConstructor( type: MessageType, oneOfEnumNames: Map, - includeDefaults: Boolean = true + includeDefaults: Boolean = true, ) { addFunction( FunctionSpec.constructorBuilder() @@ -967,14 +982,14 @@ class SwiftGenerator private constructor( addStatement("self.%1N = %1N", oneOf.name) } } - .build() + .build(), ) } private fun TypeSpec.Builder.generateMessageProperties( type: MessageType, oneOfEnumNames: Map, - forStorageType: Boolean = false + forStorageType: Boolean = false, ) { type.fields.forEach { field -> val property = PropertySpec.varBuilder(field.name, field.typeName, PUBLIC) @@ -1001,21 +1016,21 @@ class SwiftGenerator private constructor( addDoc("%N\n", oneOf.documentation.sanitizeDoc()) } } - .build() + .build(), ) } addProperty( PropertySpec.varBuilder("unknownFields", FOUNDATION_DATA, PUBLIC) .initializer(".init()") - .build() + .build(), ) } private fun TypeSpec.Builder.generateMessageStoragePropertyDelegates( type: MessageType, storageName: String, - storageType: DeclaredTypeName + storageType: DeclaredTypeName, ) { if (!type.isHeapAllocated) { println("Generating storage property delegates for a non-heap allocated type?!") @@ -1032,21 +1047,21 @@ class SwiftGenerator private constructor( writableKeyPath.parameterizedBy(storageType, propertyVariable), ) .returns(propertyVariable) - .build() - ) - .addModifiers(PUBLIC) - .getter( - FunctionSpec.getterBuilder() - .addStatement("%N[keyPath: keyPath]", storageName) - .build() + .build(), ) - .setter( - FunctionSpec.setterBuilder() - .addStatement("copyStorage()") - .addStatement("%N[keyPath: keyPath] = newValue", storageName) - .build() - ) - .build() + .addModifiers(PUBLIC) + .getter( + FunctionSpec.getterBuilder() + .addStatement("%N[keyPath: keyPath]", storageName) + .build(), + ) + .setter( + FunctionSpec.setterBuilder() + .addStatement("copyStorage()") + .addStatement("%N[keyPath: keyPath] = newValue", storageName) + .build(), + ) + .build() addProperty(subscript) } @@ -1054,7 +1069,7 @@ class SwiftGenerator private constructor( private fun TypeSpec.Builder.generateMessageOneOfs( type: MessageType, oneOfEnumNames: Map, - fileMembers: MutableList + fileMembers: MutableList, ) { type.oneOfs.forEach { oneOf -> val enumName = oneOfEnumNames.getValue(oneOf) @@ -1076,7 +1091,7 @@ class SwiftGenerator private constructor( addAttribute(deprecated) } } - .build() + .build(), ) } } @@ -1090,14 +1105,15 @@ class SwiftGenerator private constructor( oneOf.fields.forEach { field -> addStatement( "case .%1N(let %1N): try $writer.encode(tag: %2L, value: %1N)", - field.name, field.tag + field.name, + field.tag, ) } } .endControlFlow("switch") - .build() + .build(), ) - .build() + .build(), ) val equatableExtension = ExtensionSpec.builder(enumName) @@ -1136,7 +1152,7 @@ class SwiftGenerator private constructor( } } } - .build() + .build(), ) .build() fileMembers += FileMemberSpec.builder(redactableExtension) @@ -1155,7 +1171,7 @@ class SwiftGenerator private constructor( private fun generateEnum( type: EnumType, - fileMembers: MutableList + fileMembers: MutableList, ): TypeSpec { val enumName = type.typeName return TypeSpec.enumBuilder(enumName) @@ -1185,7 +1201,7 @@ class SwiftGenerator private constructor( addAttribute(deprecated) } } - .build() + .build(), ) } @@ -1201,9 +1217,9 @@ class SwiftGenerator private constructor( } } .endControlFlow("switch") - .build() + .build(), ) - .build() + .build(), ) // Swift won't synthesize CaseIterable conformance if any constants contain an availability @@ -1217,11 +1233,11 @@ class SwiftGenerator private constructor( .addStatement( "return [%L]", type.constants.map { CodeBlock.of(".%N", it.name) } - .joinToCode(",%W") + .joinToCode(",%W"), ) - .build() + .build(), ) - .build() + .build(), ) } type.nestedTypes.forEach { nestedType -> @@ -1235,14 +1251,14 @@ class SwiftGenerator private constructor( private fun generateEnclosing( type: EnclosingType, - fileMembers: MutableList + fileMembers: MutableList, ): TypeSpec { return TypeSpec.enumBuilder(type.typeName) .addModifiers(PUBLIC) .addDoc( "%N\n", "*Note:* This type only exists to maintain class structure for its nested types and " + - "is not an actual message." + "is not an actual message.", ) .apply { type.nestedTypes.forEach { nestedType -> @@ -1289,10 +1305,11 @@ class SwiftGenerator private constructor( private val NEEDS_CUSTOM_CODABLE = setOf("Duration", "Timestamp") - @JvmStatic @JvmName("get") + @JvmStatic + @JvmName("get") operator fun invoke( schema: Schema, - existingTypeModuleName: Map = emptyMap() + existingTypeModuleName: Map = emptyMap(), ): SwiftGenerator { val nameToTypeName = mutableMapOf() @@ -1341,7 +1358,7 @@ class SwiftGenerator private constructor( private fun computeReferenceCycleIndirections( schema: Schema, - existingTypes: Set + existingTypes: Set, ): Map> { val indirections = mutableMapOf>() diff --git a/wire-test-utils/src/main/java/com/squareup/wire/json/Json.kt b/wire-test-utils/src/main/java/com/squareup/wire/json/Json.kt index 2e6337d658..c8ae17c593 100644 --- a/wire-test-utils/src/main/java/com/squareup/wire/json/Json.kt +++ b/wire-test-utils/src/main/java/com/squareup/wire/json/Json.kt @@ -1,11 +1,11 @@ /* - * Copyright 2020 Square Inc. + * Copyright (C) 2020 Square, Inc. * * 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 + * https://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, @@ -14,6 +14,7 @@ * limitations under the License. */ @file:JvmName("JsonUtils") + package com.squareup.wire.json import com.squareup.moshi.JsonReader diff --git a/wire-test-utils/src/main/java/com/squareup/wire/schema/SchemaHelpers.kt b/wire-test-utils/src/main/java/com/squareup/wire/schema/SchemaHelpers.kt index d2127c638b..a348373ee2 100644 --- a/wire-test-utils/src/main/java/com/squareup/wire/schema/SchemaHelpers.kt +++ b/wire-test-utils/src/main/java/com/squareup/wire/schema/SchemaHelpers.kt @@ -1,11 +1,11 @@ /* - * Copyright (C) 2022 Block, Inc. + * Copyright (C) 2022 Square, Inc. * * 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 + * https://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, @@ -17,13 +17,13 @@ package com.squareup.wire.schema import com.squareup.wire.ProtoAdapter import com.squareup.wire.SchemaBuilder +import java.io.File import okio.Path import okio.buffer import okio.source -import java.io.File fun Schema.protoAdapter( - messageTypeName: String + messageTypeName: String, ): ProtoAdapter { return protoAdapter(messageTypeName, includeUnknown = true) } diff --git a/wire-test-utils/src/main/java/com/squareup/wire/testing/UnwantedValueStripper.kt b/wire-test-utils/src/main/java/com/squareup/wire/testing/UnwantedValueStripper.kt index 591c429180..5e4c270f1a 100644 --- a/wire-test-utils/src/main/java/com/squareup/wire/testing/UnwantedValueStripper.kt +++ b/wire-test-utils/src/main/java/com/squareup/wire/testing/UnwantedValueStripper.kt @@ -1,11 +1,11 @@ /* - * Copyright 2021 Square Inc. + * Copyright (C) 2021 Square, Inc. * * 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 + * https://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, @@ -20,7 +20,7 @@ import com.google.protobuf.DescriptorProtos.FieldDescriptorProto import com.google.protobuf.DescriptorProtos.FileDescriptorProto class UnwantedValueStripper( - val clearJsonName: Boolean = false + val clearJsonName: Boolean = false, ) { /** diff --git a/wire-test-utils/src/main/java/com/squareup/wire/testing/files.kt b/wire-test-utils/src/main/java/com/squareup/wire/testing/files.kt index 463d9ca3bd..684c1ed0ae 100644 --- a/wire-test-utils/src/main/java/com/squareup/wire/testing/files.kt +++ b/wire-test-utils/src/main/java/com/squareup/wire/testing/files.kt @@ -1,11 +1,11 @@ /* - * Copyright 2018 Square Inc. + * Copyright (C) 2018 Square, Inc. * * 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 + * https://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, @@ -15,6 +15,10 @@ */ package com.squareup.wire.testing +import java.nio.charset.Charset +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.text.Charsets.UTF_8 import okio.ByteString import okio.FileSystem import okio.Path @@ -23,16 +27,12 @@ import okio.buffer import okio.sink import org.assertj.core.api.IterableAssert import org.assertj.core.api.ListAssert -import java.nio.charset.Charset -import java.util.zip.ZipEntry -import java.util.zip.ZipOutputStream -import kotlin.text.Charsets.UTF_8 fun FileSystem.add( pathString: String, contents: String, charset: Charset = UTF_8, - bom: ByteString = ByteString.EMPTY + bom: ByteString = ByteString.EMPTY, ) { val path = pathString.toPath() if (path.parent != null) {