Fix SourceJarZipper to handle leading underscores and trailing comments.
Also improve some existing regex and add some more invalid package name tests.
PiperOrigin-RevId: 548184086
Change-Id: Ibca54f024fe0e506556b38824ff6a328b39254d8
diff --git a/tools/java/com/google/devtools/kotlin/SourceJarZipper.kt b/tools/java/com/google/devtools/kotlin/SourceJarZipper.kt
index 8748052..2ad7568 100644
--- a/tools/java/com/google/devtools/kotlin/SourceJarZipper.kt
+++ b/tools/java/com/google/devtools/kotlin/SourceJarZipper.kt
@@ -42,6 +42,7 @@
)
class SourceJarZipper : Runnable {
@Spec private lateinit var spec: CommandSpec
+
override fun run() {
throw ParameterException(spec.commandLine(), "Specify a command: zip, zip_resources or unzip")
}
@@ -129,9 +130,11 @@
)
val commonSrcs = mutableListOf<Path>()
- companion object {
+ private companion object {
const val PACKAGE_SPACE = "package "
- val PACKAGE_NAME_REGEX = "[a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z0-9_]+)*".toRegex()
+ // can't start with digit and can't be all underscores
+ val IDENTIFIER_REGEX = Regex("(?:[a-zA-Z]|_+[a-zA-Z0-9])\\w*")
+ val PACKAGE_NAME_REGEX = Regex("$IDENTIFIER_REGEX(?:\\.$IDENTIFIER_REGEX)*")
}
override fun run() {
@@ -153,9 +156,14 @@
// Kotlin allows usage of reserved words in package names framing them
// with backquote symbol "`"
val packageName =
- line.substring(PACKAGE_SPACE.length).trim().replace(";", "").replace("`", "")
+ line
+ .removePrefix(PACKAGE_SPACE)
+ .substringBefore("//")
+ .trim()
+ .removeSuffix(";")
+ .replace(Regex("\\B`(.+?)`\\B"), "$1")
if (!PACKAGE_NAME_REGEX.matches(packageName)) {
- errors.add("${this} contains an invalid package name")
+ errors.add("$this contains an invalid package name")
return this.fileName
}
return Paths.get(packageName.replace(".", "/")).resolve(this.fileName)