From 301151d2a837d21938435821079a9c20e6a7ec4e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:08:55 -0800 Subject: [PATCH 1/5] style: spotless reformat of CgtTemplateBuilder, no functional change ktlint's output for the whole file, before the ADFA-7287 change to it: tabs, and one parameter per line. It also re-indents the JSON inside the raw strings with tabs. JSON ignores that whitespace, so the templates read the same, but a built .cgt's template.json bytes differ. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../plugins/templates/CgtTemplateBuilder.kt | 607 ++++++++++-------- 1 file changed, 350 insertions(+), 257 deletions(-) diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt index 50c2a25198..364193d5e7 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt @@ -6,261 +6,354 @@ import java.io.InputStream import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream -class CgtTemplateBuilder(private val templateName: String) { - - private var description: String = "" - private var tooltipTag: String = "" - private var version: String = "1.0" - private var thumbnail: ByteArray? = null - private var showLanguage: Boolean = false - private var showMinSdk: Boolean = false - private var showPackageName: Boolean = false - private var defaultSaveLocation: String? = null - - private val textParameters = mutableListOf() - private val checkboxParameters = mutableListOf() - private val templateFiles = mutableListOf() - private val staticFiles = mutableListOf() - private val binaryFiles = mutableListOf() - - fun description(desc: String) = apply { this.description = desc } - - fun tooltipTag(tag: String) = apply { this.tooltipTag = tag } - - fun version(ver: String) = apply { this.version = ver } - - fun thumbnail(bytes: ByteArray) = apply { this.thumbnail = bytes } - - fun showLanguageOption() = apply { this.showLanguage = true } - - fun showMinSdkOption() = apply { this.showMinSdk = true } - - fun showPackageNameOption() = apply { this.showPackageName = true } - - fun defaultSaveLocation(path: String) = apply { this.defaultSaveLocation = path } - - fun thumbnailFromAssets(assetPath: String, context: PluginContext) = apply { - this.thumbnail = context.androidContext.assets.open(assetPath).use { it.readBytes() } - } - - fun addTextParameter(label: String, identifier: String, default: String? = null) = apply { - textParameters.add(TextParam(label, identifier, default)) - } - - fun addCheckboxParameter(label: String, identifier: String, default: Boolean = false) = apply { - checkboxParameters.add(CheckboxParam(label, identifier, default)) - } - - fun addTemplateFile(path: String, content: String) = apply { - templateFiles.add(FileEntry(sanitizePath(path), toPebbleSyntax(content))) - } - - fun addTemplateFromAssets(path: String, assetPath: String, context: PluginContext) = apply { - val content = context.androidContext.assets.open(assetPath) - .bufferedReader() - .use { it.readText() } - templateFiles.add(FileEntry(sanitizePath(path), content)) - } - - fun addStaticFile(path: String, content: String) = apply { - staticFiles.add(FileEntry(sanitizePath(path), content)) - } - - fun addStaticFile(path: String, bytes: ByteArray) = apply { - binaryFiles.add(BinaryFileEntry(sanitizePath(path), bytes)) - } - - fun addStaticFile(path: String, inputStream: InputStream) = apply { - binaryFiles.add(BinaryFileEntry(sanitizePath(path), inputStream.use { it.readBytes() })) - } - - fun addStaticFromAssets(path: String, assetPath: String, context: PluginContext) = apply { - val bytes = context.androidContext.assets.open(assetPath) - .use { it.readBytes() } - binaryFiles.add(BinaryFileEntry(sanitizePath(path), bytes)) - } - - fun build(outputDir: File): File { - outputDir.mkdirs() - val dirName = templateName.replace(DIR_NAME_REGEX, "") - require(dirName.isNotBlank()) { "Template name must contain at least one letter or digit" } - val outputFile = File(outputDir, "$dirName.cgt") - - ZipOutputStream(outputFile.outputStream()).use { zip -> - writeIndex(zip, dirName) - writeMetadata(zip, dirName) - writeThumbnail(zip, dirName) - writeTemplateFiles(zip, dirName) - writeStaticFiles(zip, dirName) - writeBinaryFiles(zip, dirName) - } - - return outputFile - } - - private fun sanitizePath(path: String): String { - val normalized = path.replace('\\', '/') - require(!normalized.startsWith("/")) { "Absolute paths are not allowed: $path" } - require(normalized.split('/').none { it == ".." }) { "Path traversal is not allowed: $path" } - return normalized - } - - private fun escapeJson(value: String): String = buildString(value.length) { - for (ch in value) { - when { - ch == '\\' -> append("\\\\") - ch == '"' -> append("\\\"") - ch == '\n' -> append("\\n") - ch == '\r' -> append("\\r") - ch == '\t' -> append("\\t") - ch < '\u0020' -> append("\\u${ch.code.toString(16).padStart(4, '0')}") - else -> append(ch) - } - } - } - - private fun toPebbleSyntax(content: String): String { - return content - .replace("{{", "\${{") - .replace("{%", "\${%") - .replace("{#", "\${#") - .replace("\$\${{", "\${{") - .replace("\$\${%", "\${%") - .replace("\$\${#", "\${#") - } - - private fun writeIndex(zip: ZipOutputStream, dirName: String) { - val json = """ - { - "templates": [ - { "path": "$dirName" } - ] - } - """.trimIndent() - addEntry(zip, "templates.json", json) - } - - private fun writeMetadata(zip: ZipOutputStream, dirName: String) { - val escapedName = escapeJson(templateName) - val escapedDesc = escapeJson(description) - val escapedTooltip = escapeJson(tooltipTag) - val escapedVersion = escapeJson(version) - - val optionalBlock = buildString { - val parts = mutableListOf() - if (showLanguage) parts.add(""""language": {"identifier": "LANGUAGE"}""") - if (showMinSdk) parts.add(""""minsdk": {"identifier": "MIN_SDK"}""") - if (parts.isNotEmpty()) { - append(""" - "optional": { - ${parts.joinToString(",\n ")} - }, - """.trimIndent()) - } - } - - val userBlock = buildString { - if (textParameters.isEmpty() && checkboxParameters.isEmpty()) return@buildString - - val textJson = textParameters.joinToString(",\n ") { p -> - val defaultPart = if (p.default != null) """, "default": "${escapeJson(p.default)}"""" else "" - """{"label": "${escapeJson(p.label)}", "identifier": "${escapeJson(p.identifier)}"$defaultPart}""" - } - - val checkboxJson = checkboxParameters.joinToString(",\n ") { p -> - """{"label": "${escapeJson(p.label)}", "identifier": "${escapeJson(p.identifier)}", "default": ${p.default}}""" - } - - append(""""user": {""") - if (textParameters.isNotEmpty()) { - append(""" - "text": [$textJson]""") - } - if (checkboxParameters.isNotEmpty()) { - if (textParameters.isNotEmpty()) append(",") - append(""" - "checkbox": [$checkboxJson]""") - } - append(""" - },""") - } - - val saveLocLine = defaultSaveLocation?.let { - """"defaultSaveLocation": "${escapeJson(it)}",""" - } ?: "" - - val json = """ - { - "name": "$escapedName", - "description": "$escapedDesc", - "tooltipTag": "$escapedTooltip", - "version": "$escapedVersion", - $saveLocLine - "parameters": { - "required": { - "appName": {"identifier": "APP_NAME"}, - ${if (showPackageName) """"packageName": {"identifier": "PACKAGE_NAME"},""" else ""} - "saveLocation": {"identifier": "SAVE_LOCATION"} - }, - $optionalBlock - $userBlock - "placeholder": null - }, - "system": { - "agpVersion": {"identifier": "AGP_VERSION"}, - "kotlinVersion": {"identifier": "KOTLIN_VERSION"}, - "gradleVersion": {"identifier": "GRADLE_VERSION"}, - "compileSdk": {"identifier": "COMPILE_SDK"}, - "targetSdk": {"identifier": "TARGET_SDK"}, - "javaSourceCompat": {"identifier": "JAVA_SOURCE_COMPAT"}, - "javaTargetCompat": {"identifier": "JAVA_TARGET_COMPAT"}, - "javaTarget": {"identifier": "JAVA_TARGET"} - } - } - """.trimIndent() - - addEntry(zip, "$dirName/template/template.json", json) - } - - private fun writeThumbnail(zip: ZipOutputStream, dirName: String) { - val thumbBytes = thumbnail ?: return - zip.putNextEntry(ZipEntry("$dirName/template/thumb.png")) - zip.write(thumbBytes) - zip.closeEntry() - } - - private fun writeTemplateFiles(zip: ZipOutputStream, dirName: String) { - for (file in templateFiles) { - addEntry(zip, "$dirName/${file.path}.peb", file.content) - } - } - - private fun writeStaticFiles(zip: ZipOutputStream, dirName: String) { - for (file in staticFiles) { - addEntry(zip, "$dirName/${file.path}", file.content) - } - } - - private fun writeBinaryFiles(zip: ZipOutputStream, dirName: String) { - for (file in binaryFiles) { - zip.putNextEntry(ZipEntry("$dirName/${file.path}")) - zip.write(file.bytes) - zip.closeEntry() - } - } - - private fun addEntry(zip: ZipOutputStream, path: String, content: String) { - zip.putNextEntry(ZipEntry(path)) - zip.write(content.toByteArray(Charsets.UTF_8)) - zip.closeEntry() - } - - private data class TextParam(val label: String, val identifier: String, val default: String?) - private data class CheckboxParam(val label: String, val identifier: String, val default: Boolean) - private data class FileEntry(val path: String, val content: String) - private data class BinaryFileEntry(val path: String, val bytes: ByteArray) - - companion object { - private val DIR_NAME_REGEX = Regex("[^\\p{L}\\p{N}]") - } +class CgtTemplateBuilder( + private val templateName: String, +) { + private var description: String = "" + private var tooltipTag: String = "" + private var version: String = "1.0" + private var thumbnail: ByteArray? = null + private var showLanguage: Boolean = false + private var showMinSdk: Boolean = false + private var showPackageName: Boolean = false + private var defaultSaveLocation: String? = null + + private val textParameters = mutableListOf() + private val checkboxParameters = mutableListOf() + private val templateFiles = mutableListOf() + private val staticFiles = mutableListOf() + private val binaryFiles = mutableListOf() + + fun description(desc: String) = apply { this.description = desc } + + fun tooltipTag(tag: String) = apply { this.tooltipTag = tag } + + fun version(ver: String) = apply { this.version = ver } + + fun thumbnail(bytes: ByteArray) = apply { this.thumbnail = bytes } + + fun showLanguageOption() = apply { this.showLanguage = true } + + fun showMinSdkOption() = apply { this.showMinSdk = true } + + fun showPackageNameOption() = apply { this.showPackageName = true } + + fun defaultSaveLocation(path: String) = apply { this.defaultSaveLocation = path } + + fun thumbnailFromAssets( + assetPath: String, + context: PluginContext, + ) = apply { + this.thumbnail = + context.androidContext.assets + .open(assetPath) + .use { it.readBytes() } + } + + fun addTextParameter( + label: String, + identifier: String, + default: String? = null, + ) = apply { + textParameters.add(TextParam(label, identifier, default)) + } + + fun addCheckboxParameter( + label: String, + identifier: String, + default: Boolean = false, + ) = apply { + checkboxParameters.add(CheckboxParam(label, identifier, default)) + } + + fun addTemplateFile( + path: String, + content: String, + ) = apply { + templateFiles.add(FileEntry(sanitizePath(path), toPebbleSyntax(content))) + } + + fun addTemplateFromAssets( + path: String, + assetPath: String, + context: PluginContext, + ) = apply { + val content = + context.androidContext.assets + .open(assetPath) + .bufferedReader() + .use { it.readText() } + templateFiles.add(FileEntry(sanitizePath(path), content)) + } + + fun addStaticFile( + path: String, + content: String, + ) = apply { + staticFiles.add(FileEntry(sanitizePath(path), content)) + } + + fun addStaticFile( + path: String, + bytes: ByteArray, + ) = apply { + binaryFiles.add(BinaryFileEntry(sanitizePath(path), bytes)) + } + + fun addStaticFile( + path: String, + inputStream: InputStream, + ) = apply { + binaryFiles.add(BinaryFileEntry(sanitizePath(path), inputStream.use { it.readBytes() })) + } + + fun addStaticFromAssets( + path: String, + assetPath: String, + context: PluginContext, + ) = apply { + val bytes = + context.androidContext.assets + .open(assetPath) + .use { it.readBytes() } + binaryFiles.add(BinaryFileEntry(sanitizePath(path), bytes)) + } + + fun build(outputDir: File): File { + outputDir.mkdirs() + val dirName = templateName.replace(DIR_NAME_REGEX, "") + require(dirName.isNotBlank()) { "Template name must contain at least one letter or digit" } + val outputFile = File(outputDir, "$dirName.cgt") + + ZipOutputStream(outputFile.outputStream()).use { zip -> + writeIndex(zip, dirName) + writeMetadata(zip, dirName) + writeThumbnail(zip, dirName) + writeTemplateFiles(zip, dirName) + writeStaticFiles(zip, dirName) + writeBinaryFiles(zip, dirName) + } + + return outputFile + } + + private fun sanitizePath(path: String): String { + val normalized = path.replace('\\', '/') + require(!normalized.startsWith("/")) { "Absolute paths are not allowed: $path" } + require(normalized.split('/').none { it == ".." }) { "Path traversal is not allowed: $path" } + return normalized + } + + private fun escapeJson(value: String): String = + buildString(value.length) { + for (ch in value) { + when { + ch == '\\' -> append("\\\\") + ch == '"' -> append("\\\"") + ch == '\n' -> append("\\n") + ch == '\r' -> append("\\r") + ch == '\t' -> append("\\t") + ch < '\u0020' -> append("\\u${ch.code.toString(16).padStart(4, '0')}") + else -> append(ch) + } + } + } + + private fun toPebbleSyntax(content: String): String = + content + .replace("{{", "\${{") + .replace("{%", "\${%") + .replace("{#", "\${#") + .replace("\$\${{", "\${{") + .replace("\$\${%", "\${%") + .replace("\$\${#", "\${#") + + private fun writeIndex( + zip: ZipOutputStream, + dirName: String, + ) { + val json = + """ + { + "templates": [ + { "path": "$dirName" } + ] + } + """.trimIndent() + addEntry(zip, "templates.json", json) + } + + private fun writeMetadata( + zip: ZipOutputStream, + dirName: String, + ) { + val escapedName = escapeJson(templateName) + val escapedDesc = escapeJson(description) + val escapedTooltip = escapeJson(tooltipTag) + val escapedVersion = escapeJson(version) + + val optionalBlock = + buildString { + val parts = mutableListOf() + if (showLanguage) parts.add(""""language": {"identifier": "LANGUAGE"}""") + if (showMinSdk) parts.add(""""minsdk": {"identifier": "MIN_SDK"}""") + if (parts.isNotEmpty()) { + append( + """ + "optional": { + ${parts.joinToString(",\n ")} + }, + """.trimIndent(), + ) + } + } + + val userBlock = + buildString { + if (textParameters.isEmpty() && checkboxParameters.isEmpty()) return@buildString + + val textJson = + textParameters.joinToString(",\n ") { p -> + val defaultPart = if (p.default != null) """, "default": "${escapeJson(p.default)}"""" else "" + """{"label": "${escapeJson(p.label)}", "identifier": "${escapeJson(p.identifier)}"$defaultPart}""" + } + + val checkboxJson = + checkboxParameters.joinToString(",\n ") { p -> + """{"label": "${escapeJson(p.label)}", "identifier": "${escapeJson(p.identifier)}", "default": ${p.default}}""" + } + + append(""""user": {""") + if (textParameters.isNotEmpty()) { + append( + """ + "text": [$textJson]""", + ) + } + if (checkboxParameters.isNotEmpty()) { + if (textParameters.isNotEmpty()) append(",") + append( + """ + "checkbox": [$checkboxJson]""", + ) + } + append( + """ + },""", + ) + } + + val saveLocLine = + defaultSaveLocation?.let { + """"defaultSaveLocation": "${escapeJson(it)}",""" + } ?: "" + + val json = + """ + { + "name": "$escapedName", + "description": "$escapedDesc", + "tooltipTag": "$escapedTooltip", + "version": "$escapedVersion", + $saveLocLine + "parameters": { + "required": { + "appName": {"identifier": "APP_NAME"}, + ${if (showPackageName) """"packageName": {"identifier": "PACKAGE_NAME"},""" else ""} + "saveLocation": {"identifier": "SAVE_LOCATION"} + }, + $optionalBlock + $userBlock + "placeholder": null + }, + "system": { + "agpVersion": {"identifier": "AGP_VERSION"}, + "kotlinVersion": {"identifier": "KOTLIN_VERSION"}, + "gradleVersion": {"identifier": "GRADLE_VERSION"}, + "compileSdk": {"identifier": "COMPILE_SDK"}, + "targetSdk": {"identifier": "TARGET_SDK"}, + "javaSourceCompat": {"identifier": "JAVA_SOURCE_COMPAT"}, + "javaTargetCompat": {"identifier": "JAVA_TARGET_COMPAT"}, + "javaTarget": {"identifier": "JAVA_TARGET"} + } + } + """.trimIndent() + + addEntry(zip, "$dirName/template/template.json", json) + } + + private fun writeThumbnail( + zip: ZipOutputStream, + dirName: String, + ) { + val thumbBytes = thumbnail ?: return + zip.putNextEntry(ZipEntry("$dirName/template/thumb.png")) + zip.write(thumbBytes) + zip.closeEntry() + } + + private fun writeTemplateFiles( + zip: ZipOutputStream, + dirName: String, + ) { + for (file in templateFiles) { + addEntry(zip, "$dirName/${file.path}.peb", file.content) + } + } + + private fun writeStaticFiles( + zip: ZipOutputStream, + dirName: String, + ) { + for (file in staticFiles) { + addEntry(zip, "$dirName/${file.path}", file.content) + } + } + + private fun writeBinaryFiles( + zip: ZipOutputStream, + dirName: String, + ) { + for (file in binaryFiles) { + zip.putNextEntry(ZipEntry("$dirName/${file.path}")) + zip.write(file.bytes) + zip.closeEntry() + } + } + + private fun addEntry( + zip: ZipOutputStream, + path: String, + content: String, + ) { + zip.putNextEntry(ZipEntry(path)) + zip.write(content.toByteArray(Charsets.UTF_8)) + zip.closeEntry() + } + + private data class TextParam( + val label: String, + val identifier: String, + val default: String?, + ) + + private data class CheckboxParam( + val label: String, + val identifier: String, + val default: Boolean, + ) + + private data class FileEntry( + val path: String, + val content: String, + ) + + private data class BinaryFileEntry( + val path: String, + val bytes: ByteArray, + ) + + companion object { + private val DIR_NAME_REGEX = Regex("[^\\p{L}\\p{N}]") + } } From d2ae433b84563fe8500832c980ca410a64bf97a5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:22:26 -0800 Subject: [PATCH 2/5] ADFA-7287: Stop rewriting unchanged plugin templates at every start Plugins build and register their .cgt templates in activate(), which runs at every start. CgtTemplateBuilder left each zip entry's time unset, so ZipOutputStream stamped the current time, and both the build and the registration wrote unconditionally. Each start therefore wrote every template twice, with the same contents and a new checksum. - CgtTemplateBuilder gives every entry a fixed time (1980-02-01 00:00 local, Gradle's choice for reproducible archives), builds the zip in memory, and writes the file only when its bytes differ. - IdeTemplateServiceImpl.registerTemplate() copies only when the registered copy is missing or differs, and then skips the template list reload too. It still returns true. Tests: CgtTemplateBuilderTest (4) and IdeTemplateServiceImplRegisterTest (3) pass, as do PluginTemplateCleanupTest and PluginManagerTemplateWiringTest. With the fixed time and the two content checks taken out, the four tests aimed at them fail for the reasons they name, and the three guard tests still pass. :plugin-api:apiCheck passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../plugins/templates/CgtTemplateBuilder.kt | 29 +++++- .../templates/CgtTemplateBuilderTest.kt | 83 +++++++++++++++++ .../services/IdeTemplateServiceImpl.kt | 8 ++ .../IdeTemplateServiceImplRegisterTest.kt | 88 +++++++++++++++++++ 4 files changed, 204 insertions(+), 4 deletions(-) create mode 100644 plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt index 364193d5e7..ce04279fe1 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt @@ -1,8 +1,11 @@ package com.itsaky.androidide.plugins.templates import com.itsaky.androidide.plugins.PluginContext +import java.io.ByteArrayOutputStream import java.io.File import java.io.InputStream +import java.util.Calendar +import java.util.GregorianCalendar import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream @@ -125,7 +128,8 @@ class CgtTemplateBuilder( require(dirName.isNotBlank()) { "Template name must contain at least one letter or digit" } val outputFile = File(outputDir, "$dirName.cgt") - ZipOutputStream(outputFile.outputStream()).use { zip -> + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> writeIndex(zip, dirName) writeMetadata(zip, dirName) writeThumbnail(zip, dirName) @@ -134,6 +138,12 @@ class CgtTemplateBuilder( writeBinaryFiles(zip, dirName) } + // Plugins build their templates on every activation, so leave an identical file alone + // rather than rewrite it at each start (ADFA-7287). + val cgt = bytes.toByteArray() + if (!outputFile.hasContent(cgt)) { + outputFile.writeBytes(cgt) + } return outputFile } @@ -287,7 +297,7 @@ class CgtTemplateBuilder( dirName: String, ) { val thumbBytes = thumbnail ?: return - zip.putNextEntry(ZipEntry("$dirName/template/thumb.png")) + zip.putNextEntry(entry("$dirName/template/thumb.png")) zip.write(thumbBytes) zip.closeEntry() } @@ -315,7 +325,7 @@ class CgtTemplateBuilder( dirName: String, ) { for (file in binaryFiles) { - zip.putNextEntry(ZipEntry("$dirName/${file.path}")) + zip.putNextEntry(entry("$dirName/${file.path}")) zip.write(file.bytes) zip.closeEntry() } @@ -326,11 +336,17 @@ class CgtTemplateBuilder( path: String, content: String, ) { - zip.putNextEntry(ZipEntry(path)) + zip.putNextEntry(entry(path)) zip.write(content.toByteArray(Charsets.UTF_8)) zip.closeEntry() } + // An entry without a time gets the current one, which would make every build of the same + // template differ. + private fun entry(path: String) = ZipEntry(path).apply { time = fixedEntryTime() } + + private fun File.hasContent(bytes: ByteArray) = isFile && length() == bytes.size.toLong() && readBytes().contentEquals(bytes) + private data class TextParam( val label: String, val identifier: String, @@ -355,5 +371,10 @@ class CgtTemplateBuilder( companion object { private val DIR_NAME_REGEX = Regex("[^\\p{L}\\p{N}]") + + // 1980-02-01 00:00 local time, the time Gradle gives entries of reproducible archives. + // ZipEntry stores local DOS time, so taking it in the current zone stores the same time in + // every zone. February rather than January keeps it after the DOS epoch (1980-01-01). + internal fun fixedEntryTime() = GregorianCalendar(1980, Calendar.FEBRUARY, 1).timeInMillis } } diff --git a/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt new file mode 100644 index 0000000000..d4cd8dc2bb --- /dev/null +++ b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt @@ -0,0 +1,83 @@ +package com.itsaky.androidide.plugins.templates + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.util.TimeZone +import java.util.zip.ZipFile + +/** + * Plugins build their templates on every activation (ADFA-7287). The same template must give the + * same bytes, and building it again must leave the file alone. + */ +class CgtTemplateBuilderTest { + @get:Rule + val tmp = TemporaryFolder() + + @Test + fun everyEntryHasTheFixedTime() { + val cgt = template().build(tmp.newFolder()) + + ZipFile(cgt).use { zip -> + val entries = zip.entries().toList() + assertThat(entries).isNotEmpty() + for (entry in entries) { + assertWithMessage(entry.name).that(entry.time).isEqualTo(CgtTemplateBuilder.fixedEntryTime()) + } + } + } + + @Test + fun sameTemplateGivesTheSameBytesInAnotherTimeZone() { + val zone = TimeZone.getDefault() + try { + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Kiritimati")) + val east = template().build(tmp.newFolder()).readBytes() + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Pago_Pago")) + val west = template().build(tmp.newFolder()).readBytes() + + assertThat(west).isEqualTo(east) + } finally { + TimeZone.setDefault(zone) + } + } + + @Test + fun buildingAgainLeavesAnIdenticalFileAlone() { + val dir = tmp.newFolder() + val cgt = template().build(dir) + val old = 1_000_000_000_000L + assertThat(cgt.setLastModified(old)).isTrue() + + template().build(dir) + + assertWithMessage("the identical .cgt was written again").that(cgt.lastModified()).isEqualTo(old) + } + + @Test + fun buildingAChangedTemplateReplacesTheFile() { + val dir = tmp.newFolder() + template().build(dir) + + val cgt = template(description = "Changed").build(dir) + + assertThat(templateJson(cgt)).contains("\"description\": \"Changed\"") + } + + private fun template(description: String = "A test template") = + CgtTemplateBuilder("Test App") + .description(description) + .thumbnail(byteArrayOf(1, 2, 3)) + .addTextParameter("Package name", "NPM_NAME", "my-app") + .addTemplateFile("README.md", "# {{ APP_NAME }}") + .addStaticFile(".gitignore", "node_modules/") + .addStaticFile("data.bin", byteArrayOf(4, 5, 6)) + + private fun templateJson(cgt: File): String = + ZipFile(cgt).use { zip -> + zip.getInputStream(zip.getEntry("TestApp/template/template.json")).bufferedReader().readText() + } +} diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt index b02a2a1ac7..29442106bb 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt @@ -37,6 +37,12 @@ class IdeTemplateServiceImpl( val destFile = File(Environment.TEMPLATES_DIR, prefixedName(cgtFile.name)) return try { + // Plugins register their templates on every activation. An identical copy is left + // alone, and the template list has nothing new to reload (ADFA-7287). + if (destFile.hasSameContentAs(cgtFile)) { + log.debug("Plugin $pluginId template unchanged: ${destFile.name}") + return true + } cgtFile.copyTo(destFile, overwrite = true) log.info("Plugin $pluginId registered template: ${destFile.name}") runCatching { onTemplatesChanged() } @@ -77,6 +83,8 @@ class IdeTemplateServiceImpl( private fun otherPluginIds() = loadedPluginIds() - pluginId + private fun File.hasSameContentAs(other: File) = isFile && length() == other.length() && readBytes().contentEquals(other.readBytes()) + override fun reloadTemplates() { onTemplatesChanged() } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt new file mode 100644 index 0000000000..328f80afe5 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt @@ -0,0 +1,88 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.utils.Environment +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File + +/** + * Plugins register their templates on every activation (ADFA-7287). Registering an unchanged + * template must leave the registered copy alone and not reload the template list. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class IdeTemplateServiceImplRegisterTest { + private val previous = Environment.TEMPLATES_DIR + private lateinit var templates: File + private lateinit var pluginDir: File + private var reloads = 0 + + @Before + fun pointTemplatesAtATempFolder() { + val files = RuntimeEnvironment.getApplication().filesDir + templates = File(files, "templates").apply { mkdirs() } + pluginDir = File(files, "plugin").apply { mkdirs() } + Environment.TEMPLATES_DIR = templates + } + + @After + fun restoreTemplatesFolder() { + Environment.TEMPLATES_DIR = previous + } + + @Test + fun registeringAnUnchangedTemplateLeavesTheCopyAlone() { + val cgt = File(pluginDir, "Starter.cgt").apply { writeText("v1") } + val service = service() + assertThat(service.registerTemplate(cgt)).isTrue() + val copy = File(templates, "plugin_com.example.my_Starter.cgt") + val old = 1_000_000_000_000L + assertThat(copy.setLastModified(old)).isTrue() + + assertThat(service.registerTemplate(cgt)).isTrue() + + assertWithMessage("the identical copy was written again").that(copy.lastModified()).isEqualTo(old) + assertWithMessage("template list reloads").that(reloads).isEqualTo(1) + } + + @Test + fun registeringAChangedTemplateReplacesTheCopy() { + val cgt = File(pluginDir, "Starter.cgt").apply { writeText("v1") } + val service = service() + service.registerTemplate(cgt) + + cgt.writeText("v2") + assertThat(service.registerTemplate(cgt)).isTrue() + + assertThat(File(templates, "plugin_com.example.my_Starter.cgt").readText()).isEqualTo("v2") + assertWithMessage("template list reloads").that(reloads).isEqualTo(2) + } + + @Test + fun registeringADeletedCopyAgainRestoresIt() { + val cgt = File(pluginDir, "Starter.cgt").apply { writeText("v1") } + val service = service() + service.registerTemplate(cgt) + service.cleanupAllTemplates() + + assertThat(service.registerTemplate(cgt)).isTrue() + + assertThat(File(templates, "plugin_com.example.my_Starter.cgt").readText()).isEqualTo("v1") + } + + private fun service() = + IdeTemplateServiceImpl( + "com.example.my", + setOf(PluginPermission.FILESYSTEM_WRITE), + { reloads++ }, + { listOf("com.example.my") }, + ) +} From 45d04034be07fa39644823b3a39dbbc2d61e1d79 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:42:59 -0800 Subject: [PATCH 3/5] style: spotless reformat of IdeTemplateService, no functional change Tabs for spaces, and no blank line after the interface's opening brace, before the next commit adds KDoc to it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../plugins/services/IdeTemplateService.kt | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt index 82bb621fb0..07dcc8a107 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt @@ -4,16 +4,15 @@ import com.itsaky.androidide.plugins.templates.CgtTemplateBuilder import java.io.File interface IdeTemplateService { + fun createTemplateBuilder(name: String): CgtTemplateBuilder - fun createTemplateBuilder(name: String): CgtTemplateBuilder + fun registerTemplate(cgtFile: File): Boolean - fun registerTemplate(cgtFile: File): Boolean + fun unregisterTemplate(templateFileName: String): Boolean - fun unregisterTemplate(templateFileName: String): Boolean + fun isTemplateRegistered(templateFileName: String): Boolean - fun isTemplateRegistered(templateFileName: String): Boolean + fun getRegisteredTemplates(): List - fun getRegisteredTemplates(): List - - fun reloadTemplates() + fun reloadTemplates() } From 07c5418ec626b6f5750095b07ac2baefbd9efb35 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:48:00 -0800 Subject: [PATCH 4/5] ADFA-7287: Address the independent review - registerTemplate() compares the two files in 8 KB chunks instead of reading both whole, since a plugin may register a template of any size. In both comparisons a failed read counts as a difference, so the write is tried, as it was before. - CgtTemplateBuilderTest changes one byte of a template without changing its length, so it pins the byte comparison: with length-only comparisons the changed-template tests fail. IdeTemplateServiceImplRegisterTest adds a 20,000-byte template that differs only in its last byte. - The time-zone test uses Tokyo and Los Angeles, 17 hours apart in 1980, and its failure message no longer prints both byte arrays. - KDoc on CgtTemplateBuilder.build() and IdeTemplateService.registerTemplate() says an identical file is left untouched and no change is reported. - The new log line uses {} placeholders. The template-list reload that registerTemplate() now skips for an identical copy was a no-op already: nothing calls PluginManager.setTemplateReloadListener(). The template list rescans the folder by itself. Tests: CgtTemplateBuilderTest 4, IdeTemplateServiceImplRegisterTest 4, PluginTemplateCleanupTest 3, PluginManagerTemplateWiringTest 3, all pass. :plugin-api:apiCheck passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../plugins/services/IdeTemplateService.kt | 7 ++++ .../plugins/templates/CgtTemplateBuilder.kt | 15 +++++++- .../templates/CgtTemplateBuilderTest.kt | 33 +++++++++-------- .../services/IdeTemplateServiceImpl.kt | 36 +++++++++++++++++-- .../IdeTemplateServiceImplRegisterTest.kt | 21 +++++++++-- 5 files changed, 90 insertions(+), 22 deletions(-) diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt index 07dcc8a107..acf5a0ac72 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt @@ -6,6 +6,13 @@ import java.io.File interface IdeTemplateService { fun createTemplateBuilder(name: String): CgtTemplateBuilder + /** + * Copies [cgtFile] into the IDE's templates folder, so it is offered for new projects. Needs + * `filesystem.write`. A copy that already holds the same bytes is left untouched and no change + * is reported, so registering the same templates in every `activate()` costs only a read. + * Returns false if the permission is missing, [cgtFile] is missing or not a `.cgt`, or the copy + * fails. + */ fun registerTemplate(cgtFile: File): Boolean fun unregisterTemplate(templateFileName: String): Boolean diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt index ce04279fe1..b8362c4abb 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.templates import com.itsaky.androidide.plugins.PluginContext import java.io.ByteArrayOutputStream import java.io.File +import java.io.IOException import java.io.InputStream import java.util.Calendar import java.util.GregorianCalendar @@ -122,6 +123,12 @@ class CgtTemplateBuilder( binaryFiles.add(BinaryFileEntry(sanitizePath(path), bytes)) } + /** + * Writes the template to `/.cgt`, where `` is the template name's + * letters and digits, and returns that file. The same template always gives the same bytes, + * and a file that already holds them is left untouched, so its modification time shows when + * the template last changed, not when it was last built. + */ fun build(outputDir: File): File { outputDir.mkdirs() val dirName = templateName.replace(DIR_NAME_REGEX, "") @@ -345,7 +352,13 @@ class CgtTemplateBuilder( // template differ. private fun entry(path: String) = ZipEntry(path).apply { time = fixedEntryTime() } - private fun File.hasContent(bytes: ByteArray) = isFile && length() == bytes.size.toLong() && readBytes().contentEquals(bytes) + // A file that can't be read counts as different, so the write is tried. + private fun File.hasContent(bytes: ByteArray): Boolean = + try { + isFile && length() == bytes.size.toLong() && readBytes().contentEquals(bytes) + } catch (e: IOException) { + false + } private data class TextParam( val label: String, diff --git a/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt index d4cd8dc2bb..1370d4f063 100644 --- a/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt +++ b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt @@ -34,12 +34,13 @@ class CgtTemplateBuilderTest { fun sameTemplateGivesTheSameBytesInAnotherTimeZone() { val zone = TimeZone.getDefault() try { - TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Kiritimati")) - val east = template().build(tmp.newFolder()).readBytes() - TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Pago_Pago")) - val west = template().build(tmp.newFolder()).readBytes() + // 17 hours apart in 1980. + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")) + val tokyo = template().build(tmp.newFolder()).readBytes() + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")) + val losAngeles = template().build(tmp.newFolder()).readBytes() - assertThat(west).isEqualTo(east) + assertWithMessage("the bytes differ between time zones").that(losAngeles.contentEquals(tokyo)).isTrue() } finally { TimeZone.setDefault(zone) } @@ -60,24 +61,26 @@ class CgtTemplateBuilderTest { @Test fun buildingAChangedTemplateReplacesTheFile() { val dir = tmp.newFolder() - template().build(dir) + val before = template().build(dir).length() - val cgt = template(description = "Changed").build(dir) + // One byte changes and the length doesn't, so only a byte comparison sees the change. + val cgt = template(data = byteArrayOf(4, 5, 7)).build(dir) - assertThat(templateJson(cgt)).contains("\"description\": \"Changed\"") + assertThat(cgt.length()).isEqualTo(before) + assertThat(entry(cgt, "TestApp/data.bin")).isEqualTo(byteArrayOf(4, 5, 7)) } - private fun template(description: String = "A test template") = + private fun template(data: ByteArray = byteArrayOf(4, 5, 6)) = CgtTemplateBuilder("Test App") - .description(description) + .description("A test template") .thumbnail(byteArrayOf(1, 2, 3)) .addTextParameter("Package name", "NPM_NAME", "my-app") .addTemplateFile("README.md", "# {{ APP_NAME }}") .addStaticFile(".gitignore", "node_modules/") - .addStaticFile("data.bin", byteArrayOf(4, 5, 6)) + .addStaticFile("data.bin", data) - private fun templateJson(cgt: File): String = - ZipFile(cgt).use { zip -> - zip.getInputStream(zip.getEntry("TestApp/template/template.json")).bufferedReader().readText() - } + private fun entry( + cgt: File, + name: String, + ): ByteArray = ZipFile(cgt).use { zip -> zip.getInputStream(zip.getEntry(name)).readBytes() } } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt index 29442106bb..f01e10c90a 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt @@ -6,7 +6,9 @@ import com.itsaky.androidide.plugins.services.IdeTemplateService import com.itsaky.androidide.plugins.templates.CgtTemplateBuilder import com.itsaky.androidide.utils.Environment import org.slf4j.LoggerFactory +import java.io.DataInputStream import java.io.File +import java.io.IOException class IdeTemplateServiceImpl( private val pluginId: String, @@ -18,6 +20,7 @@ class IdeTemplateServiceImpl( private val log = LoggerFactory.getLogger(IdeTemplateServiceImpl::class.java) private const val PLUGIN_PREFIX = "plugin_" private const val CGT_EXTENSION = "cgt" + private const val COMPARE_CHUNK = 8192 } private fun prefixedName(fileName: String): String = "${PLUGIN_PREFIX}${pluginId}_$fileName" @@ -38,9 +41,9 @@ class IdeTemplateServiceImpl( val destFile = File(Environment.TEMPLATES_DIR, prefixedName(cgtFile.name)) return try { // Plugins register their templates on every activation. An identical copy is left - // alone, and the template list has nothing new to reload (ADFA-7287). + // alone, and there is no change to report (ADFA-7287). if (destFile.hasSameContentAs(cgtFile)) { - log.debug("Plugin $pluginId template unchanged: ${destFile.name}") + log.debug("Plugin {} template unchanged: {}", pluginId, destFile.name) return true } cgtFile.copyTo(destFile, overwrite = true) @@ -83,7 +86,34 @@ class IdeTemplateServiceImpl( private fun otherPluginIds() = loadedPluginIds() - pluginId - private fun File.hasSameContentAs(other: File) = isFile && length() == other.length() && readBytes().contentEquals(other.readBytes()) + // Compared in chunks, not read whole: a plugin may register a template of any size, such as one + // built from the user's project. A failed read counts as a difference, so the copy is made. + private fun File.hasSameContentAs(other: File): Boolean = + try { + isFile && length() == other.length() && sameBytes(this, other) + } catch (e: IOException) { + false + } + + private fun sameBytes( + x: File, + y: File, + ): Boolean = + DataInputStream(x.inputStream().buffered()).use { a -> + DataInputStream(y.inputStream().buffered()).use { b -> + val bufA = ByteArray(COMPARE_CHUNK) + val bufB = ByteArray(COMPARE_CHUNK) + var n = a.read(bufA) + while (n != -1) { + b.readFully(bufB, 0, n) + for (i in 0 until n) { + if (bufA[i] != bufB[i]) return false + } + n = a.read(bufA) + } + true + } + } override fun reloadTemplates() { onTemplatesChanged() diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt index 328f80afe5..4238cb9fde 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt @@ -15,7 +15,7 @@ import java.io.File /** * Plugins register their templates on every activation (ADFA-7287). Registering an unchanged - * template must leave the registered copy alone and not reload the template list. + * template must leave the registered copy alone and report no change. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) @@ -50,7 +50,7 @@ class IdeTemplateServiceImplRegisterTest { assertThat(service.registerTemplate(cgt)).isTrue() assertWithMessage("the identical copy was written again").that(copy.lastModified()).isEqualTo(old) - assertWithMessage("template list reloads").that(reloads).isEqualTo(1) + assertWithMessage("change reports").that(reloads).isEqualTo(1) } @Test @@ -63,7 +63,22 @@ class IdeTemplateServiceImplRegisterTest { assertThat(service.registerTemplate(cgt)).isTrue() assertThat(File(templates, "plugin_com.example.my_Starter.cgt").readText()).isEqualTo("v2") - assertWithMessage("template list reloads").that(reloads).isEqualTo(2) + assertWithMessage("change reports").that(reloads).isEqualTo(2) + } + + @Test + fun registeringATemplateChangedOnlyInItsLastByteReplacesTheCopy() { + // Longer than one comparison chunk, so the difference is in a later chunk. + val bytes = ByteArray(20_000) { it.toByte() } + val cgt = File(pluginDir, "Starter.cgt").apply { writeBytes(bytes) } + val service = service() + service.registerTemplate(cgt) + + bytes[bytes.lastIndex] = (bytes.last() + 1).toByte() + cgt.writeBytes(bytes) + assertThat(service.registerTemplate(cgt)).isTrue() + + assertThat(File(templates, "plugin_com.example.my_Starter.cgt").readBytes()).isEqualTo(bytes) } @Test From 3f153ea3ce2b3d5cbccc07c4d60b4f39d74a4dc6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 24 Nov 2026 14:56:06 -0800 Subject: [PATCH 5/5] ADFA-7287: Address the re-review - sameBytes() also checks that the plugin's .cgt has ended, in case it grew after its length was read. Before, a longer .cgt compared equal to a copy that matched its first part. - A comparison that cannot read a file now logs that at debug level before it falls back to writing. Two tests cover that path: a built .cgt and a registered copy that are unreadable, the same length and different in content are written again. With either catch no longer catching IOException, those two tests fail. They skip when the test runs as root, which can read any file. - KDoc: build() promises the same bytes on one device, not everywhere (deflate output depends on the runtime's zlib), and names its IllegalArgumentException. registerTemplate() costs reading both files, not one. Tests: CgtTemplateBuilderTest 5, IdeTemplateServiceImplRegisterTest 5, PluginTemplateCleanupTest 3 and PluginManagerTemplateWiringTest 3 pass, none skipped. :plugin-api:apiCheck passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAXGyHbMzjSsi2zbrkw --- .../plugins/services/IdeTemplateService.kt | 3 ++- .../plugins/templates/CgtTemplateBuilder.kt | 11 ++++++++--- .../plugins/templates/CgtTemplateBuilderTest.kt | 15 +++++++++++++++ .../manager/services/IdeTemplateServiceImpl.kt | 4 +++- .../IdeTemplateServiceImplRegisterTest.kt | 16 ++++++++++++++++ 5 files changed, 44 insertions(+), 5 deletions(-) diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt index acf5a0ac72..3053e7a7b2 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeTemplateService.kt @@ -9,7 +9,8 @@ interface IdeTemplateService { /** * Copies [cgtFile] into the IDE's templates folder, so it is offered for new projects. Needs * `filesystem.write`. A copy that already holds the same bytes is left untouched and no change - * is reported, so registering the same templates in every `activate()` costs only a read. + * is reported, so registering the same templates in every `activate()` costs only reading both + * files. * Returns false if the permission is missing, [cgtFile] is missing or not a `.cgt`, or the copy * fails. */ diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt index b8362c4abb..e74a0e8c39 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilder.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.templates import com.itsaky.androidide.plugins.PluginContext +import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException @@ -125,9 +126,11 @@ class CgtTemplateBuilder( /** * Writes the template to `/.cgt`, where `` is the template name's - * letters and digits, and returns that file. The same template always gives the same bytes, - * and a file that already holds them is left untouched, so its modification time shows when - * the template last changed, not when it was last built. + * letters and digits, and returns that file. On one device, building the same template again + * gives the same bytes, and a file that already holds them is left untouched, so its + * modification time shows when the template last changed, not when it was last built. + * + * @throws IllegalArgumentException if the template name has no letter or digit. */ fun build(outputDir: File): File { outputDir.mkdirs() @@ -357,6 +360,7 @@ class CgtTemplateBuilder( try { isFile && length() == bytes.size.toLong() && readBytes().contentEquals(bytes) } catch (e: IOException) { + log.debug("Cannot read {}, so it is written again", this, e) false } @@ -383,6 +387,7 @@ class CgtTemplateBuilder( ) companion object { + private val log = LoggerFactory.getLogger(CgtTemplateBuilder::class.java) private val DIR_NAME_REGEX = Regex("[^\\p{L}\\p{N}]") // 1980-02-01 00:00 local time, the time Gradle gives entries of reproducible archives. diff --git a/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt index 1370d4f063..f1ee85d383 100644 --- a/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt +++ b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.templates import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage +import org.junit.Assume.assumeFalse import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -70,6 +71,20 @@ class CgtTemplateBuilderTest { assertThat(entry(cgt, "TestApp/data.bin")).isEqualTo(byteArrayOf(4, 5, 7)) } + @Test + fun buildingOverAnUnreadableFileWritesIt() { + val dir = tmp.newFolder() + val cgt = template().build(dir) + cgt.writeBytes(ByteArray(cgt.length().toInt())) + assertThat(cgt.setReadable(false)).isTrue() + assumeFalse("root can read any file", cgt.canRead()) + + template().build(dir) + + assertThat(cgt.setReadable(true)).isTrue() + assertThat(cgt.readBytes().contentEquals(template().build(tmp.newFolder()).readBytes())).isTrue() + } + private fun template(data: ByteArray = byteArrayOf(4, 5, 6)) = CgtTemplateBuilder("Test App") .description("A test template") diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt index f01e10c90a..14ffd8d326 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImpl.kt @@ -92,6 +92,7 @@ class IdeTemplateServiceImpl( try { isFile && length() == other.length() && sameBytes(this, other) } catch (e: IOException) { + log.debug("Cannot compare {} with {}, so it is copied", this, other, e) false } @@ -111,7 +112,8 @@ class IdeTemplateServiceImpl( } n = a.read(bufA) } - true + // y may have grown since its length was read. + b.read() == -1 } } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt index 4238cb9fde..d04b9d552b 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt @@ -5,6 +5,7 @@ import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.utils.Environment import org.junit.After +import org.junit.Assume.assumeFalse import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -81,6 +82,21 @@ class IdeTemplateServiceImplRegisterTest { assertThat(File(templates, "plugin_com.example.my_Starter.cgt").readBytes()).isEqualTo(bytes) } + @Test + fun registeringOverAnUnreadableCopyReplacesIt() { + val cgt = File(pluginDir, "Starter.cgt").apply { writeText("v1") } + val service = service() + service.registerTemplate(cgt) + val copy = File(templates, "plugin_com.example.my_Starter.cgt") + assertThat(copy.setReadable(false)).isTrue() + assumeFalse("root can read any file", copy.canRead()) + + cgt.writeText("v2") + assertThat(service.registerTemplate(cgt)).isTrue() + + assertThat(copy.readText()).isEqualTo("v2") + } + @Test fun registeringADeletedCopyAgainRestoresIt() { val cgt = File(pluginDir, "Starter.cgt").apply { writeText("v1") }