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..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 @@ -4,16 +4,23 @@ import com.itsaky.androidide.plugins.templates.CgtTemplateBuilder import java.io.File interface IdeTemplateService { + fun createTemplateBuilder(name: String): CgtTemplateBuilder - 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 reading both + * files. + * Returns false if the permission is missing, [cgtFile] is missing or not a `.cgt`, or the copy + * fails. + */ + 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() } 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..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,266 +1,398 @@ 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 import java.io.InputStream +import java.util.Calendar +import java.util.GregorianCalendar 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)) + } + + /** + * Writes the template to `/.cgt`, where `` is the template name's + * 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() + 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") + + val bytes = ByteArrayOutputStream() + ZipOutputStream(bytes).use { zip -> + writeIndex(zip, dirName) + writeMetadata(zip, dirName) + writeThumbnail(zip, dirName) + writeTemplateFiles(zip, dirName) + writeStaticFiles(zip, dirName) + 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 + } + + 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(entry("$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(entry("$dirName/${file.path}")) + zip.write(file.bytes) + zip.closeEntry() + } + } + + private fun addEntry( + zip: ZipOutputStream, + path: String, + content: String, + ) { + 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() } + + // 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) { + log.debug("Cannot read {}, so it is written again", this, e) + false + } + + 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 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. + // 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..f1ee85d383 --- /dev/null +++ b/plugin-api/src/test/kotlin/com/itsaky/androidide/plugins/templates/CgtTemplateBuilderTest.kt @@ -0,0 +1,101 @@ +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 +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 { + // 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() + + assertWithMessage("the bytes differ between time zones").that(losAngeles.contentEquals(tokyo)).isTrue() + } 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() + val before = template().build(dir).length() + + // 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(cgt.length()).isEqualTo(before) + 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") + .thumbnail(byteArrayOf(1, 2, 3)) + .addTextParameter("Package name", "NPM_NAME", "my-app") + .addTemplateFile("README.md", "# {{ APP_NAME }}") + .addStaticFile(".gitignore", "node_modules/") + .addStaticFile("data.bin", data) + + 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 b02a2a1ac7..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 @@ -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" @@ -37,6 +40,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 there is no change to report (ADFA-7287). + if (destFile.hasSameContentAs(cgtFile)) { + log.debug("Plugin {} template unchanged: {}", pluginId, destFile.name) + return true + } cgtFile.copyTo(destFile, overwrite = true) log.info("Plugin $pluginId registered template: ${destFile.name}") runCatching { onTemplatesChanged() } @@ -77,6 +86,37 @@ class IdeTemplateServiceImpl( private fun otherPluginIds() = loadedPluginIds() - pluginId + // 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) { + log.debug("Cannot compare {} with {}, so it is copied", this, other, e) + 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) + } + // y may have grown since its length was read. + b.read() == -1 + } + } + 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..d04b9d552b --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/IdeTemplateServiceImplRegisterTest.kt @@ -0,0 +1,119 @@ +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.Assume.assumeFalse +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 report no change. + */ +@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("change reports").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("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 + 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") } + 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") }, + ) +}