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

Fix an edge case in enum prefix stripping #246

Merged
merged 4 commits into from
May 8, 2024
Merged
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
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ autoService = "1.1.1"
grpc-java = "1.58.0"
grpc-kotlin = "1.4.1"
kotlinLogging = "5.1.0"
kotlinPoet = "1.14.2"
kotlinPoet = "1.16.0"
kotlinx-coroutines = "1.6.0"
kotlinx-serialization = "1.6.3"
ktlint = "1.2.1"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ private class EnumGenerator(
addCode(
buildCodeBlock {
beginControlFlow("return when (value)")
cases().forEach(::addStatement)
e.values.distinctBy { it.number }.forEach {
addStatement("%L -> %N", it.number, it.valueName)
}
addStatement("else -> UNRECOGNIZED(value)")
endControlFlowWithoutNewline()
}
Expand All @@ -129,9 +131,4 @@ private class EnumGenerator(
.build()
)
}

private fun cases() =
e.values
.distinctBy { it.number }
.map { "${it.number} -> ${it.valueName}" }
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ class EnumParser(
fun toEnum(): Enum {
val enumTypeNamePrefixToStrip =
(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, desc.name) + '_')
.takeIf { desc.valueList.all { e -> e.name.startsWith(it) } }
.takeIf {
desc.valueList.all { e ->
e.name.startsWith(it) && e.name.length > it.length && !e.name[it.length].isDigit()
}
}

val simpleNames = enclosingMessages + desc.name

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,8 @@ enum AnEnumTypeLowerCase {
AN_ENUM_TYPE_LOWER_CASE_FIRST = 1;
AN_ENUM_TYPE_lower_CASE_SECOND = 2;
}

enum AnEnumTypeInvalidWithoutPrefix {
AN_ENUM_TYPE_INVALID_WITHOUT_PREFIX_UNSPECIFIED = 0;
AN_ENUM_TYPE_INVALID_WITHOUT_PREFIX_1_FOO = 1;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,9 @@ class EnumsWithSharedPrefixTest {
AnEnumTypeLowerCase.AN_ENUM_TYPE_LOWER_CASE_UNSPECIFIED
AnEnumTypeLowerCase.AN_ENUM_TYPE_LOWER_CASE_FIRST
AnEnumTypeLowerCase.AN_ENUM_TYPE_lower_CASE_SECOND

// not stripped, some enum names are not valid without the prefix
AnEnumTypeInvalidWithoutPrefix.AN_ENUM_TYPE_INVALID_WITHOUT_PREFIX_UNSPECIFIED
AnEnumTypeInvalidWithoutPrefix.AN_ENUM_TYPE_INVALID_WITHOUT_PREFIX_1_FOO
}
}