[tool] Add Kotlin autoformatting (#5374)

Updates the tooling to fetch and use `ktfmt` for Kotlin code, the same way it currently does for the Google Java formatter, and applies that formatting (in the default mode; see discussion in the linked issue) to the repository.

In the future we could revisit the formatter or mode, but since this currently seems to be the most consistent with our other languages and to google3 formatting this is likely the option we'll want to stick with.

Fixes https://github.com/flutter/flutter/issues/118756
This commit is contained in:
stuartmorgan
2023-11-13 08:18:25 -08:00
committed by GitHub
parent 17bd92e8a3
commit 72de224b08
31 changed files with 1811 additions and 1255 deletions

View File

@ -131,10 +131,11 @@ targets:
target_file: repo_checks.yaml target_file: repo_checks.yaml
channel: master channel: master
version_file: flutter_master.version version_file: flutter_master.version
# The format check requires clang-format. # The format check requires clang-format, and the current version of ktfmt requires JDK 11+.
dependencies: >- dependencies: >-
[ [
{"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"} {"dependency": "clang", "version": "git_revision:5d5aba78dbbee75508f01bcaa69aedb2ab79065a"},
{"dependency": "open_jdk", "version": "version:17"}
] ]
- name: Linux dart_unit_test_shard_1 master - name: Linux dart_unit_test_shard_1 master

View File

@ -5,6 +5,4 @@ package dev.flutter.packages.animations.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,5 +5,4 @@ package com.example.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package dev.flutter.plugins.file_selector_example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package dev.flutter.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package com.example.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,5 +5,4 @@ package io.flutter.packages.flutter_markdown_example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package com.example.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,6 +5,4 @@ package io.flutter.packages.palettegenerator.imagecolors
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -153,7 +153,7 @@ private class PigeonApiImplementation: ExampleHostApi {
override fun add(a: Long, b: Long): Long { override fun add(a: Long, b: Long): Long {
if (a < 0L || b < 0L) { if (a < 0L || b < 0L) {
throw FlutterError("code", "message", "details"); throw FlutterError("code", "message", "details")
} }
return a + b return a + b
} }
@ -258,9 +258,7 @@ private class PigeonFlutterApi {
} }
fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) { fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) {
flutterApi!!.flutterMethod(aString) { flutterApi!!.flutterMethod(aString) { echo -> callback(Result.success(echo)) }
echo -> callback(Result.success(echo))
}
} }
} }
``` ```

View File

@ -5,10 +5,9 @@
package dev.flutter.pigeon_example_app package dev.flutter.pigeon_example_app
import ExampleHostApi import ExampleHostApi
import FlutterError
import MessageData import MessageData
import MessageFlutterApi import MessageFlutterApi
import FlutterError
import androidx.annotation.NonNull import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngine
@ -22,7 +21,7 @@ private class PigeonApiImplementation: ExampleHostApi {
override fun add(a: Long, b: Long): Long { override fun add(a: Long, b: Long): Long {
if (a < 0L || b < 0L) { if (a < 0L || b < 0L) {
throw FlutterError("code", "message", "details"); throw FlutterError("code", "message", "details")
} }
return a + b return a + b
} }
@ -47,9 +46,7 @@ private class PigeonFlutterApi {
} }
fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) { fun callFlutterMethod(aString: String, callback: (Result<String>) -> Unit) {
flutterApi!!.flutterMethod(aString) { flutterApi!!.flutterMethod(aString) { echo -> callback(Result.success(echo)) }
echo -> callback(Result.success(echo))
}
} }
} }
// #enddocregion kotlin-class-flutter // #enddocregion kotlin-class-flutter
@ -59,6 +56,6 @@ class MainActivity: FlutterActivity() {
super.configureFlutterEngine(flutterEngine) super.configureFlutterEngine(flutterEngine)
val api = PigeonApiImplementation() val api = PigeonApiImplementation()
ExampleHostApi.setUp(flutterEngine.dartExecutor.binaryMessenger, api); ExampleHostApi.setUp(flutterEngine.dartExecutor.binaryMessenger, api)
} }
} }

View File

@ -4,7 +4,6 @@
// Autogenerated from Pigeon, do not edit directly. // Autogenerated from Pigeon, do not edit directly.
// See also: https://pub.dev/packages/pigeon // See also: https://pub.dev/packages/pigeon
import android.util.Log import android.util.Log
import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
@ -19,25 +18,23 @@ private fun wrapResult(result: Any?): List<Any?> {
private fun wrapError(exception: Throwable): List<Any?> { private fun wrapError(exception: Throwable): List<Any?> {
if (exception is FlutterError) { if (exception is FlutterError) {
return listOf( return listOf(exception.code, exception.message, exception.details)
exception.code,
exception.message,
exception.details
)
} else { } else {
return listOf( return listOf(
exception.javaClass.simpleName, exception.javaClass.simpleName,
exception.toString(), exception.toString(),
"Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception))
)
} }
} }
private fun createConnectionError(channelName: String): FlutterError { private fun createConnectionError(channelName: String): FlutterError {
return FlutterError("channel-error", "Unable to establish connection on channel: '$channelName'.", "")} return FlutterError(
"channel-error", "Unable to establish connection on channel: '$channelName'.", "")
}
/** /**
* Error class for passing custom error details to Flutter via a thrown PlatformException. * Error class for passing custom error details to Flutter via a thrown PlatformException.
*
* @property code The error code. * @property code The error code.
* @property message The error message. * @property message The error message.
* @property details The error details. Must be a datatype supported by the api codec. * @property details The error details. Must be a datatype supported by the api codec.
@ -65,7 +62,6 @@ data class MessageData (
val description: String? = null, val description: String? = null,
val code: Code, val code: Code,
val data: Map<String?, String?> val data: Map<String?, String?>
) { ) {
companion object { companion object {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
@ -77,6 +73,7 @@ data class MessageData (
return MessageData(name, description, code, data) return MessageData(name, description, code, data)
} }
} }
fun toList(): List<Any?> { fun toList(): List<Any?> {
return listOf<Any?>( return listOf<Any?>(
name, name,
@ -92,13 +89,12 @@ private object ExampleHostApiCodec : StandardMessageCodec() {
override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? {
return when (type) { return when (type) {
128.toByte() -> { 128.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let { return (readValue(buffer) as? List<Any?>)?.let { MessageData.fromList(it) }
MessageData.fromList(it)
}
} }
else -> super.readValueOfType(type, buffer) else -> super.readValueOfType(type, buffer)
} }
} }
override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { override fun writeValue(stream: ByteArrayOutputStream, value: Any?) {
when (value) { when (value) {
is MessageData -> { is MessageData -> {
@ -113,19 +109,23 @@ private object ExampleHostApiCodec : StandardMessageCodec() {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */ /** Generated interface from Pigeon that represents a handler of messages from Flutter. */
interface ExampleHostApi { interface ExampleHostApi {
fun getHostLanguage(): String fun getHostLanguage(): String
fun add(a: Long, b: Long): Long fun add(a: Long, b: Long): Long
fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit) fun sendMessage(message: MessageData, callback: (Result<Boolean>) -> Unit)
companion object { companion object {
/** The codec used by ExampleHostApi. */ /** The codec used by ExampleHostApi. */
val codec: MessageCodec<Any?> by lazy { val codec: MessageCodec<Any?> by lazy { ExampleHostApiCodec }
ExampleHostApiCodec
}
/** Sets up an instance of `ExampleHostApi` to handle messages through the `binaryMessenger`. */ /** Sets up an instance of `ExampleHostApi` to handle messages through the `binaryMessenger`. */
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun setUp(binaryMessenger: BinaryMessenger, api: ExampleHostApi?) { fun setUp(binaryMessenger: BinaryMessenger, api: ExampleHostApi?) {
run { run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage", codec) val channel =
BasicMessageChannel<Any?>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage",
codec)
if (api != null) { if (api != null) {
channel.setMessageHandler { _, reply -> channel.setMessageHandler { _, reply ->
var wrapped: List<Any?> var wrapped: List<Any?>
@ -141,7 +141,11 @@ interface ExampleHostApi {
} }
} }
run { run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add", codec) val channel =
BasicMessageChannel<Any?>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add",
codec)
if (api != null) { if (api != null) {
channel.setMessageHandler { message, reply -> channel.setMessageHandler { message, reply ->
val args = message as List<Any?> val args = message as List<Any?>
@ -160,7 +164,11 @@ interface ExampleHostApi {
} }
} }
run { run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage", codec) val channel =
BasicMessageChannel<Any?>(
binaryMessenger,
"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage",
codec)
if (api != null) { if (api != null) {
channel.setMessageHandler { message, reply -> channel.setMessageHandler { message, reply ->
val args = message as List<Any?> val args = message as List<Any?>
@ -187,25 +195,29 @@ interface ExampleHostApi {
class MessageFlutterApi(private val binaryMessenger: BinaryMessenger) { class MessageFlutterApi(private val binaryMessenger: BinaryMessenger) {
companion object { companion object {
/** The codec used by MessageFlutterApi. */ /** The codec used by MessageFlutterApi. */
val codec: MessageCodec<Any?> by lazy { val codec: MessageCodec<Any?> by lazy { StandardMessageCodec() }
StandardMessageCodec()
}
} }
fun flutterMethod(aStringArg: String?, callback: (Result<String>) -> Unit) { fun flutterMethod(aStringArg: String?, callback: (Result<String>) -> Unit) {
val channelName = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod" val channelName = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod"
val channel = BasicMessageChannel<Any?>(binaryMessenger, channelName, codec) val channel = BasicMessageChannel<Any?>(binaryMessenger, channelName, codec)
channel.send(listOf(aStringArg)) { channel.send(listOf(aStringArg)) {
if (it is List<*>) { if (it is List<*>) {
if (it.size > 1) { if (it.size > 1) {
callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?))); callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?)))
} else if (it[0] == null) { } else if (it[0] == null) {
callback(Result.failure(FlutterError("null-error", "Flutter api returned null value for non-null return value.", ""))); callback(
Result.failure(
FlutterError(
"null-error",
"Flutter api returned null value for non-null return value.",
"")))
} else { } else {
val output = it[0] as String val output = it[0] as String
callback(Result.success(output)); callback(Result.success(output))
} }
} else { } else {
callback(Result.failure(createConnectionError(channelName))); callback(Result.failure(createConnectionError(channelName)))
} }
} }
} }

View File

@ -5,16 +5,9 @@
package com.example.test_plugin package com.example.test_plugin
import androidx.annotation.NonNull import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
/** /** This plugin handles the native side of the integration tests in example/integration_test/. */
* This plugin handles the native side of the integration tests in
* example/integration_test/.
*/
class TestPlugin : FlutterPlugin, HostIntegrationCoreApi { class TestPlugin : FlutterPlugin, HostIntegrationCoreApi {
var flutterApi: FlutterIntegrationCoreApi? = null var flutterApi: FlutterIntegrationCoreApi? = null
@ -23,13 +16,11 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
flutterApi = FlutterIntegrationCoreApi(binding.getBinaryMessenger()) flutterApi = FlutterIntegrationCoreApi(binding.getBinaryMessenger())
} }
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) { override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {}
}
// HostIntegrationCoreApi // HostIntegrationCoreApi
override fun noop() { override fun noop() {}
}
override fun echoAllTypes(everything: AllTypes): AllTypes { override fun echoAllTypes(everything: AllTypes): AllTypes {
return everything return everything
@ -40,15 +31,15 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
} }
override fun throwError(): Any? { override fun throwError(): Any? {
throw Exception("An error"); throw Exception("An error")
} }
override fun throwErrorFromVoid() { override fun throwErrorFromVoid() {
throw Exception("An error"); throw Exception("An error")
} }
override fun throwFlutterError(): Any? { override fun throwFlutterError(): Any? {
throw FlutterError("code", "message", "details"); throw FlutterError("code", "message", "details")
} }
override fun echoInt(anInt: Long): Long { override fun echoInt(anInt: Long): Long {
@ -99,8 +90,15 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
return AllClassesWrapper(AllNullableTypes(aNullableString = nullableString)) return AllClassesWrapper(AllNullableTypes(aNullableString = nullableString))
} }
override fun sendMultipleNullableTypes(aNullableBool: Boolean?, aNullableInt: Long?, aNullableString: String?): AllNullableTypes { override fun sendMultipleNullableTypes(
return AllNullableTypes(aNullableBool = aNullableBool, aNullableInt = aNullableInt, aNullableString = aNullableString) aNullableBool: Boolean?,
aNullableInt: Long?,
aNullableString: String?
): AllNullableTypes {
return AllNullableTypes(
aNullableBool = aNullableBool,
aNullableInt = aNullableInt,
aNullableString = aNullableString)
} }
override fun echoNullableInt(aNullableInt: Long?): Long? { override fun echoNullableInt(aNullableInt: Long?): Long? {
@ -159,7 +157,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
callback(Result.success(everything)) callback(Result.success(everything))
} }
override fun echoAsyncNullableAllNullableTypes(everything: AllNullableTypes?, callback: (Result<AllNullableTypes?>) -> Unit) { override fun echoAsyncNullableAllNullableTypes(
everything: AllNullableTypes?,
callback: (Result<AllNullableTypes?>) -> Unit
) {
callback(Result.success(everything)) callback(Result.success(everything))
} }
@ -191,7 +192,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
callback(Result.success(aList)) callback(Result.success(aList))
} }
override fun echoAsyncMap(aMap: Map<String?, Any?>, callback: (Result<Map<String?, Any?>>) -> Unit) { override fun echoAsyncMap(
aMap: Map<String?, Any?>,
callback: (Result<Map<String?, Any?>>) -> Unit
) {
callback(Result.success(aMap)) callback(Result.success(aMap))
} }
@ -215,7 +219,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
callback(Result.success(aString)) callback(Result.success(aString))
} }
override fun echoAsyncNullableUint8List(aUint8List: ByteArray?, callback: (Result<ByteArray?>) -> Unit) { override fun echoAsyncNullableUint8List(
aUint8List: ByteArray?,
callback: (Result<ByteArray?>) -> Unit
) {
callback(Result.success(aUint8List)) callback(Result.success(aUint8List))
} }
@ -227,7 +234,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
callback(Result.success(aList)) callback(Result.success(aList))
} }
override fun echoAsyncNullableMap(aMap: Map<String?, Any?>?, callback: (Result<Map<String?, Any?>?>) -> Unit) { override fun echoAsyncNullableMap(
aMap: Map<String?, Any?>?,
callback: (Result<Map<String?, Any?>?>) -> Unit
) {
callback(Result.success(aMap)) callback(Result.success(aMap))
} }
@ -242,6 +252,7 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
override fun callFlutterThrowError(callback: (Result<Any?>) -> Unit) { override fun callFlutterThrowError(callback: (Result<Any?>) -> Unit) {
flutterApi!!.throwError() { result -> callback(result) } flutterApi!!.throwError() { result -> callback(result) }
} }
override fun callFlutterThrowErrorFromVoid(callback: (Result<Unit>) -> Unit) { override fun callFlutterThrowErrorFromVoid(callback: (Result<Unit>) -> Unit) {
flutterApi!!.throwErrorFromVoid() { result -> callback(result) } flutterApi!!.throwErrorFromVoid() { result -> callback(result) }
} }
@ -256,8 +267,8 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
aNullableString: String?, aNullableString: String?,
callback: (Result<AllNullableTypes>) -> Unit callback: (Result<AllNullableTypes>) -> Unit
) { ) {
flutterApi!!.sendMultipleNullableTypes(aNullableBool, aNullableInt, aNullableString) { flutterApi!!.sendMultipleNullableTypes(aNullableBool, aNullableInt, aNullableString) { echo ->
echo -> callback(echo) callback(echo)
} }
} }
@ -285,7 +296,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
flutterApi!!.echoList(aList) { echo -> callback(echo) } flutterApi!!.echoList(aList) { echo -> callback(echo) }
} }
override fun callFlutterEchoMap(aMap: Map<String?, Any?>, callback: (Result<Map<String?, Any?>>) -> Unit) { override fun callFlutterEchoMap(
aMap: Map<String?, Any?>,
callback: (Result<Map<String?, Any?>>) -> Unit
) {
flutterApi!!.echoMap(aMap) { echo -> callback(echo) } flutterApi!!.echoMap(aMap) { echo -> callback(echo) }
} }
@ -293,7 +307,10 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
flutterApi!!.echoEnum(anEnum) { echo -> callback(echo) } flutterApi!!.echoEnum(anEnum) { echo -> callback(echo) }
} }
override fun callFlutterEchoAllNullableTypes(everything: AllNullableTypes?, callback: (Result<AllNullableTypes?>) -> Unit) { override fun callFlutterEchoAllNullableTypes(
everything: AllNullableTypes?,
callback: (Result<AllNullableTypes?>) -> Unit
) {
flutterApi!!.echoAllNullableTypes(everything) { echo -> callback(echo) } flutterApi!!.echoAllNullableTypes(everything) { echo -> callback(echo) }
} }
@ -305,28 +322,42 @@ class TestPlugin: FlutterPlugin, HostIntegrationCoreApi {
flutterApi!!.echoNullableInt(anInt) { echo -> callback(echo) } flutterApi!!.echoNullableInt(anInt) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableDouble(aDouble: Double?, callback: (Result<Double?>) -> Unit) { override fun callFlutterEchoNullableDouble(
aDouble: Double?,
callback: (Result<Double?>) -> Unit
) {
flutterApi!!.echoNullableDouble(aDouble) { echo -> callback(echo) } flutterApi!!.echoNullableDouble(aDouble) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableString(aString: String?, callback: (Result<String?>) -> Unit) { override fun callFlutterEchoNullableString(
aString: String?,
callback: (Result<String?>) -> Unit
) {
flutterApi!!.echoNullableString(aString) { echo -> callback(echo) } flutterApi!!.echoNullableString(aString) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableUint8List(aList: ByteArray?, callback: (Result<ByteArray?>) -> Unit) { override fun callFlutterEchoNullableUint8List(
aList: ByteArray?,
callback: (Result<ByteArray?>) -> Unit
) {
flutterApi!!.echoNullableUint8List(aList) { echo -> callback(echo) } flutterApi!!.echoNullableUint8List(aList) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableList(aList: List<Any?>?, callback: (Result<List<Any?>?>) -> Unit) { override fun callFlutterEchoNullableList(
aList: List<Any?>?,
callback: (Result<List<Any?>?>) -> Unit
) {
flutterApi!!.echoNullableList(aList) { echo -> callback(echo) } flutterApi!!.echoNullableList(aList) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableMap(aMap: Map<String?, Any?>?, callback: (Result<Map<String?, Any?>?>) -> Unit) { override fun callFlutterEchoNullableMap(
aMap: Map<String?, Any?>?,
callback: (Result<Map<String?, Any?>?>) -> Unit
) {
flutterApi!!.echoNullableMap(aMap) { echo -> callback(echo) } flutterApi!!.echoNullableMap(aMap) { echo -> callback(echo) }
} }
override fun callFlutterEchoNullableEnum(anEnum: AnEnum?, callback: (Result<AnEnum?>) -> Unit) { override fun callFlutterEchoNullableEnum(anEnum: AnEnum?, callback: (Result<AnEnum?>) -> Unit) {
flutterApi!!.echoNullableEnum(anEnum) { echo -> callback(echo) } flutterApi!!.echoNullableEnum(anEnum) { echo -> callback(echo) }
} }
} }

View File

@ -7,11 +7,10 @@ package com.example.test_plugin
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.mockk.every import io.mockk.every
import io.mockk.mockk import io.mockk.mockk
import junit.framework.TestCase
import org.junit.Test
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.ArrayList import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
internal class AllDatatypesTest : TestCase() { internal class AllDatatypesTest : TestCase() {
fun compareAllTypes(firstTypes: AllTypes?, secondTypes: AllTypes?) { fun compareAllTypes(firstTypes: AllTypes?, secondTypes: AllTypes?) {
@ -59,7 +58,8 @@ internal class AllDatatypesTest: TestCase() {
val binaryMessenger = mockk<BinaryMessenger>() val binaryMessenger = mockk<BinaryMessenger>()
val api = FlutterIntegrationCoreApi(binaryMessenger) val api = FlutterIntegrationCoreApi(binaryMessenger)
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterIntegrationCoreApi.codec val codec = FlutterIntegrationCoreApi.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)
@ -73,7 +73,8 @@ internal class AllDatatypesTest: TestCase() {
var didCall = false var didCall = false
api.echoAllNullableTypes(everything) { api.echoAllNullableTypes(everything) {
didCall = true didCall = true
val output = (it.getOrNull())?.let { val output =
(it.getOrNull())?.let {
assertNull(it.aNullableBool) assertNull(it.aNullableBool)
assertNull(it.aNullableInt) assertNull(it.aNullableInt)
assertNull(it.aNullableDouble) assertNull(it.aNullableDouble)
@ -87,7 +88,6 @@ internal class AllDatatypesTest: TestCase() {
assertNull(it.nullableMapWithObject) assertNull(it.nullableMapWithObject)
} }
assertNotNull(output) assertNotNull(output)
} }
assertTrue(didCall) assertTrue(didCall)
@ -95,7 +95,8 @@ internal class AllDatatypesTest: TestCase() {
@Test @Test
fun testHasValues() { fun testHasValues() {
val everything = AllNullableTypes( val everything =
AllNullableTypes(
aNullableBool = false, aNullableBool = false,
aNullableInt = 1234L, aNullableInt = 1234L,
aNullableDouble = 2.0, aNullableDouble = 2.0,
@ -112,7 +113,8 @@ internal class AllDatatypesTest: TestCase() {
val binaryMessenger = mockk<BinaryMessenger>() val binaryMessenger = mockk<BinaryMessenger>()
val api = FlutterIntegrationCoreApi(binaryMessenger) val api = FlutterIntegrationCoreApi(binaryMessenger)
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterIntegrationCoreApi.codec val codec = FlutterIntegrationCoreApi.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)
@ -141,7 +143,24 @@ internal class AllDatatypesTest: TestCase() {
assertNotNull(list[1]) assertNotNull(list[1])
assertTrue(list[1] == 123L) assertTrue(list[1] == 123L)
val list2 = listOf(null, 123, null, null, null, null, null, null, null, null, null, null, null, null, null, null) val list2 =
listOf(
null,
123,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null)
val everything2 = AllNullableTypes.fromList(list2) val everything2 = AllNullableTypes.fromList(list2)
assertEquals(everything.aNullableInt, everything2.aNullableInt) assertEquals(everything.aNullableInt, everything2.aNullableInt)

View File

@ -9,10 +9,9 @@ import io.mockk.every
import io.mockk.mockk import io.mockk.mockk
import io.mockk.slot import io.mockk.slot
import io.mockk.verify import io.mockk.verify
import java.nio.ByteBuffer
import junit.framework.TestCase import junit.framework.TestCase
import org.junit.Test import org.junit.Test
import java.nio.ByteBuffer
internal class AsyncHandlersTest : TestCase() { internal class AsyncHandlersTest : TestCase() {
@Test @Test
@ -22,7 +21,8 @@ internal class AsyncHandlersTest: TestCase() {
val value = "Test" val value = "Test"
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterIntegrationCoreApi.codec val codec = FlutterIntegrationCoreApi.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)
@ -44,8 +44,7 @@ internal class AsyncHandlersTest: TestCase() {
binaryMessenger.send( binaryMessenger.send(
"dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString", "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString",
any(), any(),
any() any())
)
} }
} }
@ -61,10 +60,12 @@ internal class AsyncHandlersTest: TestCase() {
val channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" val channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo"
every { every {
binaryMessenger.setMessageHandler("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid", any()) binaryMessenger.setMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid", any())
} returns Unit } returns Unit
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { api.echo(any(), any()) } answers { every { api.echo(any(), any()) } answers
{
val callback = arg<(Result<String>) -> Unit>(1) val callback = arg<(Result<String>) -> Unit>(1)
callback(Result.success(output)) callback(Result.success(output))
} }
@ -77,12 +78,9 @@ internal class AsyncHandlersTest: TestCase() {
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
assertNotNull(it) assertNotNull(it)
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as MutableList<Any>?
val wrapped = codec.decodeMessage(it) as MutableList<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(output, wrapped.first()) }
assertEquals(output, wrapped.first())
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -100,9 +98,11 @@ internal class AsyncHandlersTest: TestCase() {
every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit
every { every {
binaryMessenger.setMessageHandler("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo", any()) binaryMessenger.setMessageHandler(
"dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo", any())
} returns Unit } returns Unit
every { api.voidVoid(any()) } answers { every { api.voidVoid(any()) } answers
{
val callback = arg<() -> Unit>(0) val callback = arg<() -> Unit>(0)
callback() callback()
} }
@ -113,8 +113,7 @@ internal class AsyncHandlersTest: TestCase() {
val message = codec.encodeMessage(null) val message = codec.encodeMessage(null)
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as MutableList<Any>?
val wrapped = codec.decodeMessage(it) as MutableList<Any>?
assertNull(wrapped) assertNull(wrapped)
} }

View File

@ -6,21 +6,15 @@ package com.example.test_plugin
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MessageCodec import io.flutter.plugin.common.MessageCodec
import io.flutter.plugin.common.StandardMessageCodec
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.ArrayList import java.util.ArrayList
internal class EchoBinaryMessenger(private val codec: MessageCodec<Any?>) : BinaryMessenger { internal class EchoBinaryMessenger(private val codec: MessageCodec<Any?>) : BinaryMessenger {
override fun send(channel: String, message: ByteBuffer?) { override fun send(channel: String, message: ByteBuffer?) {
// Method not implemented because this messenger is just for echoing. // Method not implemented because this messenger is just for echoing.
} }
override fun send( override fun send(channel: String, message: ByteBuffer?, callback: BinaryMessenger.BinaryReply?) {
channel: String,
message: ByteBuffer?,
callback: BinaryMessenger.BinaryReply?
) {
message?.rewind() message?.rewind()
val args = codec.decodeMessage(message) as ArrayList<*> val args = codec.decodeMessage(message) as ArrayList<*>
val replyData = codec.encodeMessage(args) val replyData = codec.encodeMessage(args)
@ -28,11 +22,7 @@ internal class EchoBinaryMessenger(private val codec: MessageCodec<Any?>): Binar
callback?.reply(replyData) callback?.reply(replyData)
} }
override fun setMessageHandler( override fun setMessageHandler(channel: String, handler: BinaryMessenger.BinaryMessageHandler?) {
channel: String,
handler: BinaryMessenger.BinaryMessageHandler?
) {
// Method not implemented because this messenger is just for echoing. // Method not implemented because this messenger is just for echoing.
} }
} }

View File

@ -9,10 +9,10 @@ import io.mockk.every
import io.mockk.mockk import io.mockk.mockk
import io.mockk.slot import io.mockk.slot
import io.mockk.verify import io.mockk.verify
import junit.framework.TestCase
import org.junit.Test
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.ArrayList import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
internal class EnumTest : TestCase() { internal class EnumTest : TestCase() {
@Test @Test
@ -35,8 +35,7 @@ internal class EnumTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let {
assertNotNull(wrapped[0]) assertNotNull(wrapped[0])
@ -55,7 +54,8 @@ internal class EnumTest: TestCase() {
val input = DataWithEnum(EnumState.SUCCESS) val input = DataWithEnum(EnumState.SUCCESS)
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = EnumApi2Flutter.codec val codec = EnumApi2Flutter.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)

View File

@ -7,10 +7,10 @@ package com.example.test_plugin
import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.BinaryMessenger
import io.mockk.every import io.mockk.every
import io.mockk.mockk import io.mockk.mockk
import junit.framework.TestCase
import org.junit.Test
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.ArrayList import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
class ListTest : TestCase() { class ListTest : TestCase() {
@Test @Test
@ -21,7 +21,8 @@ class ListTest: TestCase() {
val inside = TestMessage(listOf(1, 2, 3)) val inside = TestMessage(listOf(1, 2, 3))
val input = TestMessage(listOf(inside)) val input = TestMessage(listOf(inside))
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = FlutterSmallApi.codec val codec = FlutterSmallApi.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)

View File

@ -8,10 +8,10 @@ import io.flutter.plugin.common.BinaryMessenger
import io.mockk.every import io.mockk.every
import io.mockk.mockk import io.mockk.mockk
import io.mockk.slot import io.mockk.slot
import junit.framework.TestCase
import org.junit.Test
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.ArrayList import java.util.ArrayList
import junit.framework.TestCase
import org.junit.Test
class MultipleArityTests : TestCase() { class MultipleArityTests : TestCase() {
@Test @Test
@ -35,12 +35,9 @@ class MultipleArityTests: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(inputX - inputY, wrapped[0]) }
assertEquals(inputX - inputY, wrapped[0])
}
} }
} }
@ -52,7 +49,8 @@ class MultipleArityTests: TestCase() {
val inputX = 10L val inputX = 10L
val inputY = 5L val inputY = 5L
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = MultipleArityFlutterApi.codec val codec = MultipleArityFlutterApi.codec
val message = arg<ByteBuffer>(1) val message = arg<ByteBuffer>(1)
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)

View File

@ -33,12 +33,9 @@ class NullableReturnsTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(output, wrapped[0]) }
assertEquals(output, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -52,7 +49,8 @@ class NullableReturnsTest: TestCase() {
val output = 12L val output = 12L
every { binaryMessenger.send(any(), any(), any()) } answers { every { binaryMessenger.send(any(), any(), any()) } answers
{
val codec = NullableReturnFlutterApi.codec val codec = NullableReturnFlutterApi.codec
val reply = arg<BinaryMessenger.BinaryReply>(2) val reply = arg<BinaryMessenger.BinaryReply>(2)
val replyData = codec.encodeMessage(listOf(output)) val replyData = codec.encodeMessage(listOf(output))

View File

@ -11,8 +11,6 @@ import io.mockk.slot
import io.mockk.verify import io.mockk.verify
import junit.framework.TestCase import junit.framework.TestCase
import org.junit.Test import org.junit.Test
import java.nio.ByteBuffer
import java.util.ArrayList
class PrimitiveTest : TestCase() { class PrimitiveTest : TestCase() {
@Test @Test
@ -35,12 +33,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input.toLong(), wrapped[0]) }
assertEquals(input.toLong(), wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -83,12 +78,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -131,12 +123,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -163,12 +152,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -211,12 +197,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -259,12 +242,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -307,12 +287,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertTrue(input.contentEquals(wrapped[0] as IntArray)) }
assertTrue(input.contentEquals(wrapped[0] as IntArray))
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -355,12 +332,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -403,12 +377,9 @@ class PrimitiveTest: TestCase() {
message?.rewind() message?.rewind()
handlerSlot.captured.onMessage(message) { handlerSlot.captured.onMessage(message) {
it?.rewind() it?.rewind()
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as List<Any>?
val wrapped = codec.decodeMessage(it) as List<Any>?
assertNotNull(wrapped) assertNotNull(wrapped)
wrapped?.let { wrapped?.let { assertEquals(input, wrapped[0]) }
assertEquals(input, wrapped[0])
}
} }
verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) }
@ -430,5 +401,4 @@ class PrimitiveTest: TestCase() {
assertTrue(didCall) assertTrue(didCall)
} }
} }

View File

@ -6,5 +6,4 @@ package com.example.test_plugin_example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package dev.flutter.plaform_example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,5 +5,4 @@ package dev.flutter.rfw.examples.hello
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,5 +5,4 @@ package dev.flutter.rfw.examples.local
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -5,5 +5,4 @@ package dev.flutter.rfw.examples.remote
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -6,5 +6,4 @@ package com.example.example
import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() { class MainActivity : FlutterActivity() {}
}

View File

@ -32,9 +32,12 @@ const int _exitJavaFormatFailed = 5;
const int _exitGitFailed = 6; const int _exitGitFailed = 6;
const int _exitDependencyMissing = 7; const int _exitDependencyMissing = 7;
const int _exitSwiftFormatFailed = 8; const int _exitSwiftFormatFailed = 8;
const int _exitKotlinFormatFailed = 9;
final Uri _googleFormatterUrl = Uri.https('github.com', final Uri _javaFormatterUrl = Uri.https('github.com',
'/google/google-java-format/releases/download/google-java-format-1.3/google-java-format-1.3-all-deps.jar'); '/google/google-java-format/releases/download/google-java-format-1.3/google-java-format-1.3-all-deps.jar');
final Uri _kotlinFormatterUrl = Uri.https('maven.org',
'/maven2/com/facebook/ktfmt/0.46/ktfmt-0.46-jar-with-dependencies.jar');
/// A command to format all package code. /// A command to format all package code.
class FormatCommand extends PackageCommand { class FormatCommand extends PackageCommand {
@ -62,14 +65,15 @@ class FormatCommand extends PackageCommand {
@override @override
final String description = final String description =
'Formats the code of all packages (Java, Objective-C, C++, Dart, and ' 'Formats the code of all packages (C++, Dart, Java, Kotlin, Objective-C, '
'optionally Swift).\n\n' 'and optionally Swift).\n\n'
'This command requires "git", "flutter" and "clang-format" v5 to be in ' 'This command requires "git", "flutter", "java", and "clang-format" v5 '
'your path.'; 'to be in your path.';
@override @override
Future<void> run() async { Future<void> run() async {
final String googleFormatterPath = await _getGoogleFormatterPath(); final String javaFormatterPath = await _getJavaFormatterPath();
final String kotlinFormatterPath = await _getKotlinFormatterPath();
// This class is not based on PackageLoopingCommand because running the // This class is not based on PackageLoopingCommand because running the
// formatters separately for each package is an order of magnitude slower, // formatters separately for each package is an order of magnitude slower,
@ -77,7 +81,8 @@ class FormatCommand extends PackageCommand {
final Iterable<String> files = final Iterable<String> files =
await _getFilteredFilePaths(getFiles(), relativeTo: packagesDir); await _getFilteredFilePaths(getFiles(), relativeTo: packagesDir);
await _formatDart(files); await _formatDart(files);
await _formatJava(files, googleFormatterPath); await _formatJava(files, javaFormatterPath);
await _formatKotlin(files, kotlinFormatterPath);
await _formatCppAndObjectiveC(files); await _formatCppAndObjectiveC(files);
final String? swiftFormat = getNullableStringArg(_swiftFormatArg); final String? swiftFormat = getNullableStringArg(_swiftFormatArg);
if (swiftFormat != null) { if (swiftFormat != null) {
@ -187,8 +192,7 @@ class FormatCommand extends PackageCommand {
throw ToolExit(_exitDependencyMissing); throw ToolExit(_exitDependencyMissing);
} }
Future<void> _formatJava( Future<void> _formatJava(Iterable<String> files, String formatterPath) async {
Iterable<String> files, String googleFormatterPath) async {
final Iterable<String> javaFiles = final Iterable<String> javaFiles =
_getPathsWithExtensions(files, <String>{'.java'}); _getPathsWithExtensions(files, <String>{'.java'});
if (javaFiles.isNotEmpty) { if (javaFiles.isNotEmpty) {
@ -202,7 +206,7 @@ class FormatCommand extends PackageCommand {
print('Formatting .java files...'); print('Formatting .java files...');
final int exitCode = await _runBatched( final int exitCode = await _runBatched(
java, <String>['-jar', googleFormatterPath, '--replace'], java, <String>['-jar', formatterPath, '--replace'],
files: javaFiles); files: javaFiles);
if (exitCode != 0) { if (exitCode != 0) {
printError('Failed to format Java files: exit code $exitCode.'); printError('Failed to format Java files: exit code $exitCode.');
@ -211,6 +215,30 @@ class FormatCommand extends PackageCommand {
} }
} }
Future<void> _formatKotlin(
Iterable<String> files, String formatterPath) async {
final Iterable<String> kotlinFiles =
_getPathsWithExtensions(files, <String>{'.kt'});
if (kotlinFiles.isNotEmpty) {
final String java = getStringArg('java');
if (!await _hasDependency(java)) {
printError(
'Unable to run "java". Make sure that it is in your path, or '
'provide a full path with --java.');
throw ToolExit(_exitDependencyMissing);
}
print('Formatting .kt files...');
final int exitCode = await _runBatched(
java, <String>['-jar', formatterPath],
files: kotlinFiles);
if (exitCode != 0) {
printError('Failed to format Kotlin files: exit code $exitCode.');
throw ToolExit(_exitKotlinFormatFailed);
}
}
}
Future<void> _formatDart(Iterable<String> files) async { Future<void> _formatDart(Iterable<String> files) async {
final Iterable<String> dartFiles = final Iterable<String> dartFiles =
_getPathsWithExtensions(files, <String>{'.dart'}); _getPathsWithExtensions(files, <String>{'.dart'});
@ -283,7 +311,7 @@ class FormatCommand extends PackageCommand {
(String filePath) => extensions.contains(path.extension(filePath))); (String filePath) => extensions.contains(path.extension(filePath)));
} }
Future<String> _getGoogleFormatterPath() async { Future<String> _getJavaFormatterPath() async {
final String javaFormatterPath = path.join( final String javaFormatterPath = path.join(
path.dirname(path.fromUri(platform.script)), path.dirname(path.fromUri(platform.script)),
'google-java-format-1.3-all-deps.jar'); 'google-java-format-1.3-all-deps.jar');
@ -292,13 +320,29 @@ class FormatCommand extends PackageCommand {
if (!javaFormatterFile.existsSync()) { if (!javaFormatterFile.existsSync()) {
print('Downloading Google Java Format...'); print('Downloading Google Java Format...');
final http.Response response = await http.get(_googleFormatterUrl); final http.Response response = await http.get(_javaFormatterUrl);
javaFormatterFile.writeAsBytesSync(response.bodyBytes); javaFormatterFile.writeAsBytesSync(response.bodyBytes);
} }
return javaFormatterPath; return javaFormatterPath;
} }
Future<String> _getKotlinFormatterPath() async {
final String kotlinFormatterPath = path.join(
path.dirname(path.fromUri(platform.script)),
'ktfmt-0.46-jar-with-dependencies.jar');
final File kotlinFormatterFile =
packagesDir.fileSystem.file(kotlinFormatterPath);
if (!kotlinFormatterFile.existsSync()) {
print('Downloading ktfmt...');
final http.Response response = await http.get(_kotlinFormatterUrl);
kotlinFormatterFile.writeAsBytesSync(response.bodyBytes);
}
return kotlinFormatterPath;
}
/// Returns true if [command] can be run successfully. /// Returns true if [command] can be run successfully.
Future<bool> _hasDependency(String command) async { Future<bool> _hasDependency(String command) async {
// Some versions of Java accept both -version and --version, but some only // Some versions of Java accept both -version and --version, but some only

View File

@ -22,6 +22,7 @@ void main() {
late FormatCommand analyzeCommand; late FormatCommand analyzeCommand;
late CommandRunner<void> runner; late CommandRunner<void> runner;
late String javaFormatPath; late String javaFormatPath;
late String kotlinFormatPath;
setUp(() { setUp(() {
fileSystem = MemoryFileSystem(); fileSystem = MemoryFileSystem();
@ -34,12 +35,16 @@ void main() {
platform: mockPlatform, platform: mockPlatform,
); );
// Create the java formatter file that the command checks for, to avoid // Create the Java and Kotlin formatter files that the command checks for,
// a download. // to avoid a download.
final p.Context path = analyzeCommand.path; final p.Context path = analyzeCommand.path;
javaFormatPath = path.join(path.dirname(path.fromUri(mockPlatform.script)), javaFormatPath = path.join(path.dirname(path.fromUri(mockPlatform.script)),
'google-java-format-1.3-all-deps.jar'); 'google-java-format-1.3-all-deps.jar');
fileSystem.file(javaFormatPath).createSync(recursive: true); fileSystem.file(javaFormatPath).createSync(recursive: true);
kotlinFormatPath = path.join(
path.dirname(path.fromUri(mockPlatform.script)),
'ktfmt-0.46-jar-with-dependencies.jar');
fileSystem.file(kotlinFormatPath).createSync(recursive: true);
runner = CommandRunner<void>('format_command', 'Test for format_command'); runner = CommandRunner<void>('format_command', 'Test for format_command');
runner.addCommand(analyzeCommand); runner.addCommand(analyzeCommand);
@ -428,6 +433,62 @@ void main() {
])); ]));
}); });
group('kotlin-format', () {
test('formats .kt files', () async {
const List<String> files = <String>[
'android/src/main/kotlin/io/flutter/plugins/a_plugin/a.kt',
'android/src/main/kotlin/io/flutter/plugins/a_plugin/b.kt',
];
final RepositoryPackage plugin = createFakePlugin(
'a_plugin',
packagesDir,
extraFiles: files,
);
await runCapturingPrint(runner, <String>['format']);
expect(
processRunner.recordedCalls,
orderedEquals(<ProcessCall>[
const ProcessCall('java', <String>['-version'], null),
ProcessCall(
'java',
<String>[
'-jar',
kotlinFormatPath,
...getPackagesDirRelativePaths(plugin, files)
],
packagesDir.path),
]));
});
test('fails if Kotlin formatter fails', () async {
const List<String> files = <String>[
'android/src/main/kotlin/io/flutter/plugins/a_plugin/a.kt',
'android/src/main/kotlin/io/flutter/plugins/a_plugin/b.kt',
];
createFakePlugin('a_plugin', packagesDir, extraFiles: files);
processRunner.mockProcessesForExecutable['java'] = <FakeProcessInfo>[
FakeProcessInfo(
MockProcess(), <String>['-version']), // check for working java
FakeProcessInfo(MockProcess(exitCode: 1), <String>['-jar']), // format
];
Error? commandError;
final List<String> output = await runCapturingPrint(
runner, <String>['format'], errorHandler: (Error e) {
commandError = e;
});
expect(commandError, isA<ToolExit>());
expect(
output,
containsAllInOrder(<Matcher>[
contains('Failed to format Kotlin files: exit code 1.'),
]));
});
});
group('swift-format', () { group('swift-format', () {
test('formats Swift if --swift-format flag is provided', () async { test('formats Swift if --swift-format flag is provided', () async {
const List<String> files = <String>[ const List<String> files = <String>[