Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle date/time conversion in runtime #258

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
102 changes: 24 additions & 78 deletions plugin/src/main/java/app/cash/paraphrase/plugin/ResourceWriter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.NOTHING
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.STRING
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
Expand Down Expand Up @@ -62,6 +63,17 @@ internal fun writeResources(
.addType(
TypeSpec.objectBuilder("FormattedResources")
.apply {
addProperty(
PropertySpec.builder(
name = "dateTimeConverter",
type = Types.DateTimeConverter.parameterizedBy(ANY.copy()).copy(),
)
.addModifiers(KModifier.INTERNAL)
.mutable(true)
.initializer("%T", Types.AndroidDateTimeConverter)
.build(),
)

mergedResources.forEach { mergedResource ->
val funSpec = mergedResource.toFunSpec(packageStringsType)
addFunction(funSpec)
Expand Down Expand Up @@ -142,90 +154,25 @@ private fun Argument.toParameterSpec(): ParameterSpec =
},
)

private fun Argument.toParameterCodeBlock(): CodeBlock =
when (type) {
private fun Argument.toParameterCodeBlock(): CodeBlock {
return when (type) {
Duration::class -> CodeBlock.of("%L.inWholeSeconds", name)
LocalDate::class -> buildCodeBlock {
addCalendarInstance {
addStatement("set(%1L.year, %1L.monthValue·-·1, %1L.dayOfMonth)", name)
}
}

LocalTime::class -> buildCodeBlock {
addCalendarInstance {
addStatement("set(%T.HOUR_OF_DAY, %L.hour)", Types.Calendar, name)
addStatement("set(%T.MINUTE, %L.minute)", Types.Calendar, name)
addStatement("set(%T.SECOND, %L.second)", Types.Calendar, name)
addStatement("set(%T.MILLISECOND, %L.nano·/·1_000_000)", Types.Calendar, name)
}
}

LocalDateTime::class -> buildCodeBlock {
addCalendarInstance {
addDateTimeSetStatements(name)
}
}

// `Nothing` arg must be null, but passing null to the formatter replaces the whole format with
// "null". Passing an `Int` allows the formatter to function as expected.
Nothing::class -> CodeBlock.of("-1")

OffsetTime::class -> buildCodeBlock {
addCalendarInstance(timeZoneId = "\"GMT\${%L.offset.id}\"", name) {
addStatement("set(%T.HOUR_OF_DAY, %L.hour)", Types.Calendar, name)
addStatement("set(%T.MINUTE, %L.minute)", Types.Calendar, name)
addStatement("set(%T.SECOND, %L.second)", Types.Calendar, name)
addStatement("set(%T.MILLISECOND, %L.nano·/·1_000_000)", Types.Calendar, name)
}
}

OffsetDateTime::class -> buildCodeBlock {
addCalendarInstance(timeZoneId = "\"GMT\${%L.offset.id}\"", name) {
addDateTimeSetStatements(name)
}
}

ZonedDateTime::class -> buildCodeBlock {
addCalendarInstance(timeZoneId = "%L.zone.id", name) {
addDateTimeSetStatements(name)
}
}

ZoneOffset::class -> buildCodeBlock {
addCalendarInstance(timeZoneId = "\"GMT\${%L.id}\"", name)
}
LocalDate::class,
LocalTime::class,
LocalDateTime::class,
OffsetTime::class,
OffsetDateTime::class,
ZonedDateTime::class,
ZoneOffset::class,
-> CodeBlock.of("dateTimeConverter.convertToCalendar(%L)", name)

else -> CodeBlock.of("%L", name)
}

private fun CodeBlock.Builder.addCalendarInstance(
timeZoneId: String? = null,
vararg timeZoneIdArgs: Any? = emptyArray(),
applyBlock: (() -> Unit)? = null,
) {
val timeZoneReference = if (timeZoneId == null) "GMT_ZONE" else "getTimeZone($timeZoneId)"
add("%T.getInstance(\n⇥", Types.Calendar)
addStatement("%T.$timeZoneReference,", Types.TimeZone, *timeZoneIdArgs)
addStatement("%T.Builder().setExtension('u', \"ca-iso8601\").build(),", Types.ULocale)
add("⇤)")

if (applyBlock != null) {
add(".apply·{\n⇥")
applyBlock.invoke()
add("⇤}")
}
}

private fun CodeBlock.Builder.addDateTimeSetStatements(dateTimeArgName: String) {
add("set(\n⇥")
addStatement("%L.year,", dateTimeArgName)
addStatement("%L.monthValue·-·1,", dateTimeArgName)
addStatement("%L.dayOfMonth,", dateTimeArgName)
addStatement("%L.hour,", dateTimeArgName)
addStatement("%L.minute,", dateTimeArgName)
addStatement("%L.second,", dateTimeArgName)
add("⇤)\n")
addStatement("set(%T.MILLISECOND, %L.nano·/·1_000_000)", Types.Calendar, dateTimeArgName)
}

private fun MergedResource.Visibility.toKModifier(): KModifier {
Expand Down Expand Up @@ -278,9 +225,8 @@ private fun MergedResource.toIntOverloadFunSpec(overloaded: FunSpec): FunSpec {
}

private object Types {
val AndroidDateTimeConverter = ClassName("app.cash.paraphrase", "AndroidDateTimeConverter")
val ArrayMap = ClassName("androidx.collection", "ArrayMap")
val Calendar = ClassName("android.icu.util", "Calendar")
val DateTimeConverter = ClassName("app.cash.paraphrase", "DateTimeConverter")
val FormattedResource = ClassName("app.cash.paraphrase", "FormattedResource")
val TimeZone = ClassName("android.icu.util", "TimeZone")
val ULocale = ClassName("android.icu.util", "ULocale")
}
28 changes: 28 additions & 0 deletions runtime/api/runtime.api
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
public final class app/cash/paraphrase/AndroidDateTimeConverter : app/cash/paraphrase/DateTimeConverter {
public static final field INSTANCE Lapp/cash/paraphrase/AndroidDateTimeConverter;
public fun convertToCalendar (Ljava/time/LocalDate;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/LocalDate;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/LocalDateTime;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/LocalDateTime;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/LocalTime;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/LocalTime;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/OffsetDateTime;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/OffsetDateTime;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/OffsetTime;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/OffsetTime;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/ZoneOffset;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/ZoneOffset;)Ljava/lang/Object;
public fun convertToCalendar (Ljava/time/ZonedDateTime;)Landroid/icu/util/Calendar;
public synthetic fun convertToCalendar (Ljava/time/ZonedDateTime;)Ljava/lang/Object;
}

public abstract interface class app/cash/paraphrase/DateTimeConverter {
public abstract fun convertToCalendar (Ljava/time/LocalDate;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/LocalDateTime;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/LocalTime;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/OffsetDateTime;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/OffsetTime;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/ZoneOffset;)Ljava/lang/Object;
public abstract fun convertToCalendar (Ljava/time/ZonedDateTime;)Ljava/lang/Object;
}

public final class app/cash/paraphrase/FormattedResource {
public fun <init> (ILjava/lang/Object;)V
public fun equals (Ljava/lang/Object;)Z
Expand Down
6 changes: 6 additions & 0 deletions runtime/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,17 @@ android {
defaultConfig {
minSdk = 24
}

compileOptions {
isCoreLibraryDesugaringEnabled = true
}
}

dependencies {
api(libs.androidAnnotation)

coreLibraryDesugaring(libs.coreLibraryDesugaring)

testImplementation(libs.junit)
testImplementation(libs.truth)
}
130 changes: 130 additions & 0 deletions runtime/src/main/java/app/cash/paraphrase/AndroidDateTimeConverter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Copyright (C) 2023 Cash App
*
* 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 app.cash.paraphrase

import android.icu.util.Calendar
import android.icu.util.TimeZone
import android.icu.util.ULocale
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.ZoneOffset
import java.time.ZonedDateTime

/**
* Converts `java.time` types used by Paraphrase to a [Calendar] that can be used by ICU to format.
*/
public object AndroidDateTimeConverter : DateTimeConverter<Calendar> {

private val Iso8601Locale by lazy(LazyThreadSafetyMode.NONE) {
ULocale.Builder()
.setExtension('u', "ca-iso8601")
.build()
}
Comment on lines +35 to +39
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since AndroidDateTimeConverter is an object, this ULocale instantiation was happening immediately when FormattedResources was accessed, causing the JVM test to (still) crash. Loading it lazily avoids this.


override fun convertToCalendar(date: LocalDate): Calendar {
return Calendar.getInstance(
TimeZone.GMT_ZONE,
Iso8601Locale,
).apply {
set(date.year, date.monthValue - 1, date.dayOfMonth)
}
}

override fun convertToCalendar(time: OffsetTime): Calendar {
return Calendar.getInstance(
TimeZone.getTimeZone("GMT${time.offset.id}"),
Iso8601Locale,
).apply {
set(Calendar.HOUR_OF_DAY, time.hour)
set(Calendar.MINUTE, time.minute)
set(Calendar.SECOND, time.second)
set(Calendar.MILLISECOND, time.nano / 1_000_000)
}
}

override fun convertToCalendar(time: LocalTime): Calendar {
return Calendar.getInstance(
TimeZone.GMT_ZONE,
Iso8601Locale,
).apply {
set(Calendar.HOUR_OF_DAY, time.hour)
set(Calendar.MINUTE, time.minute)
set(Calendar.SECOND, time.second)
set(Calendar.MILLISECOND, time.nano / 1_000_000)
}
}

override fun convertToCalendar(dateTime: ZonedDateTime): Calendar {
return Calendar.getInstance(
TimeZone.getTimeZone(dateTime.zone.id),
Iso8601Locale,
).apply {
set(
dateTime.year,
dateTime.monthValue - 1,
dateTime.dayOfMonth,
dateTime.hour,
dateTime.minute,
dateTime.second,
)
set(Calendar.MILLISECOND, dateTime.nano / 1_000_000)
}
}

override fun convertToCalendar(dateTime: OffsetDateTime): Calendar {
return Calendar.getInstance(
TimeZone.getTimeZone("GMT${dateTime.offset.id}"),
Iso8601Locale,
).apply {
set(
dateTime.year,
dateTime.monthValue - 1,
dateTime.dayOfMonth,
dateTime.hour,
dateTime.minute,
dateTime.second,
)
set(Calendar.MILLISECOND, dateTime.nano / 1_000_000)
}
}

override fun convertToCalendar(dateTime: LocalDateTime): Calendar {
return Calendar.getInstance(
TimeZone.GMT_ZONE,
Iso8601Locale,
).apply {
set(
dateTime.year,
dateTime.monthValue - 1,
dateTime.dayOfMonth,
dateTime.hour,
dateTime.minute,
dateTime.second,
)
set(Calendar.MILLISECOND, dateTime.nano / 1_000_000)
}
}

override fun convertToCalendar(zoneOffset: ZoneOffset): Calendar {
return Calendar.getInstance(
TimeZone.getTimeZone("GMT${zoneOffset.id}"),
Iso8601Locale,
)
}
}
Loading