Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ class KotlinGenerator private constructor(
}
is OneOf -> {
val fieldName = newName(fieldOrOneOf.name, fieldOrOneOf)
newName(boxedOneOfClassName(fieldOrOneOf.name), boxedOneOfClassName(fieldOrOneOf.name))
newName(oneOfClassName(fieldOrOneOf), boxedOneOfClassName(fieldOrOneOf.name))
if (oneofMode != OneofMode.SEALED_CLASS) {
val keysFieldName = boxedOneOfKeysFieldName(fieldName)
check(newName(keysFieldName) == keysFieldName) {
Expand Down Expand Up @@ -3051,10 +3051,17 @@ class KotlinGenerator private constructor(
}

/**
* Converts a snake_case field name to PascalCase for use as a sealed class subtype name.
* Converts a snake_case name to CamelCase for use as a sealed oneof type name.
* For example: `card_id` → `CardId`, `bank_account` → `BankAccount`.
*/
private fun String.toSealedSubclassName(): String = split("_").joinToString("") { part -> part.replaceFirstChar { it.uppercaseChar() } }
private fun String.toCamelCase(): String = split("_").joinToString("") { part ->
part.replaceFirstChar { it.uppercaseChar() }
}

private fun oneOfClassName(oneOf: OneOf): String = when (oneofMode) {
OneofMode.SEALED_CLASS -> oneOf.name.toCamelCase()
else -> boxedOneOfClassName(oneOf.name)
}

/**
* Generates a sealed class for a oneof.
Expand Down Expand Up @@ -3324,7 +3331,7 @@ class KotlinGenerator private constructor(
private fun sealedSubclassNameAllocator(oneOf: OneOf): NameAllocator = sealedSubclassNameAllocatorStore.getOrPut(oneOf) {
NameAllocator(preallocateKeywords = !escapeKotlinKeywords).apply {
for (field in oneOf.fields) {
newName(field.name.toSealedSubclassName(), field)
newName(field.name.toCamelCase(), field)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2246,6 +2246,30 @@ class KotlinGeneratorTest {
)
}

@Test fun sealedOneofGeneratesCamelCaseClassName() {
val schema = buildSchema {
add(
"message.proto".toPath(),
"""
|syntax = "proto2";
|message PaymentMethodChoice {
| oneof payment_method {
| string card_id = 1;
| }
|}
""".trimMargin(),
)
}
val code = KotlinWithProfilesGenerator(schema)
.generateKotlin("PaymentMethodChoice", oneofMode = OneofMode.SEALED_CLASS)
assertThat(code).contains("public val payment_method: PaymentMethod? = null")
assertThat(code).contains("public sealed class PaymentMethod")
assertThat(code).contains("public data class CardId(")
assertThat(code).contains("is PaymentMethod.CardId ->")
assertThat(code).contains("1 -> payment_method = PaymentMethod.CardId(")
assertThat(code).doesNotContain("public sealed class Payment_method")
}

@Test fun sealedOneofAdapterEncodesAndDecodesCorrectly() {
val schema = buildSchema {
add(
Expand Down
Loading