From e703393b77bf9c992b88c7bf7bc54cb152fef7ed Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 15 Oct 2026 16:41:36 -0700 Subject: [PATCH 1/3] ADFA-4930: find Quick Build and plugin output via the project model Quick Build's setup.json and a plugin project's .cgp were looked up under `/build`. With relocated build output that path holds nothing, or a stale report from before the relocation, which Quick Build would then read. Both now resolve against the build directory the synced model gives: the module's for setup.json, the root project's for the .cgp. The model and the output agree because builds follow the last sync (PR 1). `QuickBuildTaskPaths.setupJson` is now relative to the build directory, and the debugging doc lists the relocated location. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 --- .../quickbuild/GradleQuickBuildProvisioner.kt | 36 +++++------ .../quickbuild/QuickBuildTaskPaths.kt | 11 ++-- .../androidide/viewmodel/BuildViewModel.kt | 20 ++++-- ...GradleQuickBuildProvisionerBuildDirTest.kt | 61 +++++++++++++++++++ .../GradleQuickBuildProvisionerFakes.kt | 15 +++-- .../quickbuild/QuickBuildTaskPathsTest.kt | 10 +-- quickbuild/docs/debugging.md | 3 +- 7 files changed, 113 insertions(+), 43 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerBuildDirTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 11fc7691fe..2218c574bf 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.projects.IProjectManager import com.itsaky.androidide.projects.api.AndroidModule import com.itsaky.androidide.projects.builder.BuildService import com.itsaky.androidide.projects.isPluginProject +import com.itsaky.androidide.projects.models.buildDir import com.itsaky.androidide.resources.R import com.itsaky.androidide.services.builder.GradleBuildService import com.itsaky.androidide.tooling.api.GradlePluginConfig @@ -459,28 +460,19 @@ class GradleQuickBuildProvisioner( // Variant-scoped, matching where the Gradle plugin writes it: one report per // debuggable variant, so a flavored project has several and only this variant's is - // the built app. - val reportPath = QuickBuildTaskPaths.setupJson(variantName) - val reportFile = - sequenceOf( - File(moduleDir, reportPath), - File(projectRoot, reportPath), - ).firstOrNull { it.isFile } - ?: run { - log.error( - "{} not found under {} or {} after the proxy app build", - reportPath, - moduleDir, - projectRoot, - ) - // The build succeeded but wrote no Quick Build setup, which all but - // names the cause: the plugin only configures DEBUGGABLE variants, and - // the release-name check above only catches AGP's own release build - // type. Say so instead of the generic "setup failed". - return ProxyAppBuildResult.Failed( - context.getString(R.string.quick_build_variant_setup_missing, variantName), - ) - } + // the built app. Under the build directory the synced model gives the module, which + // relocated build output (ADFA-4930) moves out of the project folder. + val reportFile = File(module.buildDir, QuickBuildTaskPaths.setupJson(variantName)) + if (!reportFile.isFile) { + log.error("{} not found after the proxy app build", reportFile) + // The build succeeded but wrote no Quick Build setup, which all but names the + // cause: the plugin only configures DEBUGGABLE variants, and the release-name + // check above only catches AGP's own release build type. Say so instead of the + // generic "setup failed". + return ProxyAppBuildResult.Failed( + context.getString(R.string.quick_build_variant_setup_missing, variantName), + ) + } val proxyApp = ProxyAppInfo.parse(reportFile.readText(), projectRoot) diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt index e281c677da..0a629f8fab 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt @@ -36,10 +36,11 @@ object QuickBuildTaskPaths { } /** - * Where the Gradle plugin writes that variant's proxy app report, relative to the - * directory owning the `build/` dir - the other half of the same contract, kept next to - * the task name so the two cannot drift apart. Variant-scoped like every other Quick - * Build output: a flavored project has one report per debuggable variant. + * Where the Gradle plugin writes that variant's proxy app report, relative to the module's + * build directory - the other half of the same contract, kept next to the task name so the + * two cannot drift apart. Variant-scoped like every other Quick Build output: a flavored + * project has one report per debuggable variant. Resolve it against the build directory in + * the project model: relocated build output (ADFA-4930) is not under `/build`. */ - fun setupJson(variantName: String = DEFAULT_VARIANT): String = "build/quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json" + fun setupJson(variantName: String = DEFAULT_VARIANT): String = "quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json" } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt index 87487e4420..de3770ea0d 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt @@ -14,6 +14,7 @@ import com.itsaky.androidide.projects.api.AndroidModule import com.itsaky.androidide.projects.builder.BuildService import com.itsaky.androidide.projects.isPluginProject import com.itsaky.androidide.projects.models.assembleTaskOutputListingFile +import com.itsaky.androidide.projects.models.buildDir import com.itsaky.androidide.resources.R import com.itsaky.androidide.tooling.api.messages.BuildRunType import com.itsaky.androidide.tooling.api.messages.GradleBuildParams @@ -147,15 +148,22 @@ class BuildViewModel( } if (isPluginProject) { - val projectRoot = IProjectManager.getInstance().projectDirPath + // The root project's build directory as the synced model has it, which + // relocated build output (ADFA-4930) moves out of the project folder. + val rootBuildDir = + IProjectManager + .getInstance() + .workspace + ?.rootProject + ?.buildDir val cgpFile = - withContext(Dispatchers.IO) { findPluginCgpFile(projectRoot, variant) } + rootBuildDir?.let { withContext(Dispatchers.IO) { findPluginCgpFile(it, variant) } } if (cgpFile != null) { reporter.finish(BuildState.AwaitingPluginInstall(cgpFile)) } else { - log.warn("Plugin built successfully but .cgp file not found") + log.warn("Plugin built successfully but no .cgp file under {}/plugin", rootBuildDir) reporter.finish( - BuildState.Error("Plugin built but output file (.cgp) not found in build/plugin"), + BuildState.Error("Plugin built but output file (.cgp) not found"), ) } return@launch @@ -321,10 +329,10 @@ class BuildViewModel( } private fun findPluginCgpFile( - projectRoot: String, + rootBuildDir: File, variant: AndroidModels.AndroidVariant, ): File? { - val pluginDir = File(projectRoot, "build/plugin") + val pluginDir = File(rootBuildDir, "plugin") if (!pluginDir.exists()) return null val isDebug = variant.name.contains("debug", ignoreCase = true) diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerBuildDirTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerBuildDirTest.kt new file mode 100644 index 0000000000..f1d328c60a --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerBuildDirTest.kt @@ -0,0 +1,61 @@ +package com.itsaky.androidide.quickbuild + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.appdevforall.cotg.quickbuild.service.provision.ProvisionOutcome +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File + +/** + * The proxy app report is read from the module's build directory as the synced project model + * gives it. With build output relocated off the project folder (ADFA-4930) that directory is + * not `/build`, which may still hold a report from before the relocation. + */ +@RunWith(RobolectricTestRunner::class) +class GradleQuickBuildProvisionerBuildDirTest { + @get:Rule + val temp = TemporaryFolder() + + private val context: Context get() = ApplicationProvider.getApplicationContext() + + private val projectRoot: File get() = File(temp.root, "project") + + private val moduleDir: File get() = File(projectRoot, "app").apply { mkdirs() } + + private val relocatedBuildDir: File get() = File(temp.root, "no_backup/gradle-build/project-1234/main/app-5678") + + @Test + fun `a report under a relocated build directory is found`() = + runTest { + writeSetupJson(moduleDir, buildDir = relocatedBuildDir) + + val outcome = provisioner().provision() + + assertThat(outcome).isInstanceOf(ProvisionOutcome.Success::class.java) + } + + @Test + fun `a stale report left in the project folder is not read`() = + runTest { + writeSetupJson(moduleDir, entryActivity = "com.example.demo.StaleActivity") + writeSetupJson(moduleDir, buildDir = relocatedBuildDir) + + val outcome = provisioner().provision() + + assertThat((outcome as ProvisionOutcome.Success).proxyApp.entryActivity) + .isEqualTo("com.example.demo.MainActivity") + } + + private fun provisioner(): GradleQuickBuildProvisioner = + testProvisioner( + context, + projectRoot, + projectManager = FakeProjectManager(projectRoot, appModules = listOf(androidModule(buildDir = relocatedBuildDir))), + ) +} diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt index d38c83182f..4c1bfc770a 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt @@ -143,13 +143,16 @@ internal fun unsyncedProjectManager(projectRoot: File): FakeProjectManager = Fak * @param path the module's Gradle path. * @param variantName the selected variant, or null for the mid-sync read the provisioner * falls back to the default variant on. + * @param buildDir the module's build directory as the synced model reports it. */ internal fun androidModule( path: String = ":app", variantName: String? = "debug", + buildDir: File = File("app", "build"), ): AndroidModule = mockk().also { module -> every { module.path } returns path + every { module.buildDirPath } returns buildDir.path every { module.getSelectedVariant() } returns variantName?.let { AndroidModels.AndroidVariant @@ -208,17 +211,20 @@ internal const val REAL_APPLICATION_ID = "com.example.demo" /** * Writes the report the Gradle plugin would have written for a successful proxy app build. * - * @param moduleDir the module whose `build/` dir owns the report. + * @param moduleDir the module whose `build/` dir owns the report, as [testProvisioner]'s default + * module reports it. * @param variantName the variant the report belongs to; reports are variant-scoped. * @param entryActivity the launcher activity, or null for the No-Activity template, which is a * successful build with nothing to launch. + * @param buildDir the build directory the report goes under. */ internal fun writeSetupJson( moduleDir: File, variantName: String = "debug", entryActivity: String? = "com.example.demo.MainActivity", + buildDir: File = File(moduleDir, "build"), ) { - val report = File(moduleDir, QuickBuildTaskPaths.setupJson(variantName)) + val report = File(buildDir, QuickBuildTaskPaths.setupJson(variantName)) report.parentFile.mkdirs() val apkPath = "app/build/outputs/apk/$variantName/app-$variantName.apk" report.writeText( @@ -235,7 +241,7 @@ internal fun writeUnparseableSetupJson( moduleDir: File, variantName: String = "debug", ) { - val report = File(moduleDir, QuickBuildTaskPaths.setupJson(variantName)) + val report = File(moduleDir, "build/" + QuickBuildTaskPaths.setupJson(variantName)) report.parentFile.mkdirs() // A well-formed JSON object with no proxyAppId: parseable as JSON, unusable as a report, // which is the shape a schema drift actually produces. @@ -250,7 +256,8 @@ internal fun testProvisioner( context: Context, projectRoot: File, buildService: BuildService? = FakeBuildService(), - projectManager: IProjectManager = FakeProjectManager(projectRoot, appModules = listOf(androidModule())), + projectManager: IProjectManager = + FakeProjectManager(projectRoot, appModules = listOf(androidModule(buildDir = File(projectRoot, "app/build")))), installer: ProxyAppInstaller = recordingInstaller(), packages: InstalledPackages = FakePackages(), apkCertSha256: (File) -> String? = { null }, diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt index 3408e4af87..418d2d89d2 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt @@ -73,18 +73,18 @@ class QuickBuildTaskPathsTest { @Test fun `the report path is variant-scoped, matching where the Gradle plugin writes it`() { - // Both halves of the plugin contract: `build/quickbuild//setup.json`. A + // Both halves of the plugin contract: `/quickbuild//setup.json`. A // flavor-agnostic path here would read another flavor's report - the wrong APK and // the wrong applicationId. assertThat(QuickBuildTaskPaths.setupJson("debug")) - .isEqualTo("build/quickbuild/debug/setup.json") + .isEqualTo("quickbuild/debug/setup.json") assertThat(QuickBuildTaskPaths.setupJson("demoDebug")) - .isEqualTo("build/quickbuild/demoDebug/setup.json") + .isEqualTo("quickbuild/demoDebug/setup.json") } @Test fun `a blank variant reads the default variant's report`() { - assertThat(QuickBuildTaskPaths.setupJson("")).isEqualTo("build/quickbuild/debug/setup.json") - assertThat(QuickBuildTaskPaths.setupJson()).isEqualTo("build/quickbuild/debug/setup.json") + assertThat(QuickBuildTaskPaths.setupJson("")).isEqualTo("quickbuild/debug/setup.json") + assertThat(QuickBuildTaskPaths.setupJson()).isEqualTo("quickbuild/debug/setup.json") } } diff --git a/quickbuild/docs/debugging.md b/quickbuild/docs/debugging.md index 95c13dcbb2..4c13460a1f 100644 --- a/quickbuild/docs/debugging.md +++ b/quickbuild/docs/debugging.md @@ -184,7 +184,8 @@ to CoGo. | `no_backup/quickbuild-scratch/-<16 hex>/work` | executor payload staging | `run-as com.itsaky.androidide`; **deleted on teardown** | | `no_backup/quickbuild-scratch/-<16 hex>/out` | daemon output: classes, dex, relinked resources | as above | | `/.androidide/quickbuild/generation` | the generation counter | plain `adb shell cat` | -| `//build/quickbuild/setup.json` | the proxy app build's handshake with CoGo | plain `adb shell cat` | +| `//build/quickbuild//setup.json` | the proxy app build's handshake with CoGo | plain `adb shell cat` | +| `no_backup/gradle-build/-<16 hex>/main/-<16 hex>/quickbuild//setup.json` | the same, when "Relocate build output" is on (ADFA-4930) | `run-as com.itsaky.androidide` | | `/data/data//files/quickbuild/payload/` | persisted payload: `payload.dex`, `resources.arsc`, `assets.zip`, `meta.json` | `run-as ` | Projects live under `/storage/emulated/0/CodeOnTheGoProjects/`. From b0648b8a503234e0b651c07fb6095c63bba9231a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 15 Oct 2026 17:55:18 -0700 Subject: [PATCH 2/3] ADFA-4930: pin the .cgp lookup and pass setupJson its build directory From the #2150 review: - The plugin .cgp lookup moves into `findPluginCgpFile(workspace, variantName)`, so a test can pin it to the model's root build directory. `PluginCgpLookupTest` fails against the old `/build/plugin` lookup. - `QuickBuildTaskPaths.setupJson` takes the build directory and returns a File, so a caller cannot resolve it against the module folder by mistake. - The fake module's default build directory is absolute, so it never resolves against the test JVM's working directory. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 --- .../quickbuild/GradleQuickBuildProvisioner.kt | 2 +- .../quickbuild/QuickBuildTaskPaths.kt | 19 ++++-- .../androidide/viewmodel/BuildViewModel.kt | 48 +++++++-------- .../GradleQuickBuildProvisionerFakes.kt | 6 +- .../quickbuild/QuickBuildTaskPathsTest.kt | 15 +++-- .../viewmodel/PluginCgpLookupTest.kt | 60 +++++++++++++++++++ 6 files changed, 110 insertions(+), 40 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/viewmodel/PluginCgpLookupTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt index 2218c574bf..5822ff1265 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisioner.kt @@ -462,7 +462,7 @@ class GradleQuickBuildProvisioner( // debuggable variant, so a flavored project has several and only this variant's is // the built app. Under the build directory the synced model gives the module, which // relocated build output (ADFA-4930) moves out of the project folder. - val reportFile = File(module.buildDir, QuickBuildTaskPaths.setupJson(variantName)) + val reportFile = QuickBuildTaskPaths.setupJson(module.buildDir, variantName) if (!reportFile.isFile) { log.error("{} not found after the proxy app build", reportFile) // The build succeeded but wrote no Quick Build setup, which all but names the diff --git a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt index 0a629f8fab..2b0bc3d9a7 100644 --- a/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt +++ b/app/src/main/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPaths.kt @@ -1,5 +1,7 @@ package com.itsaky.androidide.quickbuild +import java.io.File + /** * Composes the Gradle task path for the quick-build proxy app build's `assemble` task from * a module's Gradle project path and the variant CoGo has selected. @@ -36,11 +38,16 @@ object QuickBuildTaskPaths { } /** - * Where the Gradle plugin writes that variant's proxy app report, relative to the module's - * build directory - the other half of the same contract, kept next to the task name so the - * two cannot drift apart. Variant-scoped like every other Quick Build output: a flavored - * project has one report per debuggable variant. Resolve it against the build directory in - * the project model: relocated build output (ADFA-4930) is not under `/build`. + * Where the Gradle plugin writes that variant's proxy app report - the other half of the same + * contract, kept next to the task name so the two cannot drift apart. Variant-scoped like + * every other Quick Build output: a flavored project has one report per debuggable variant. + * + * @param buildDir the module's build directory as the project model has it; relocated build + * output (ADFA-4930) is not under `/build`. + * @param variantName the variant; blank falls back to [DEFAULT_VARIANT]. */ - fun setupJson(variantName: String = DEFAULT_VARIANT): String = "quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json" + fun setupJson( + buildDir: File, + variantName: String = DEFAULT_VARIANT, + ): File = File(buildDir, "quickbuild/${variantName.ifBlank { DEFAULT_VARIANT }}/setup.json") } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt index de3770ea0d..99b3209b4f 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/BuildViewModel.kt @@ -11,6 +11,7 @@ import com.itsaky.androidide.models.installTaskRequestsIn import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.projects.IProjectManager import com.itsaky.androidide.projects.api.AndroidModule +import com.itsaky.androidide.projects.api.Workspace import com.itsaky.androidide.projects.builder.BuildService import com.itsaky.androidide.projects.isPluginProject import com.itsaky.androidide.projects.models.assembleTaskOutputListingFile @@ -148,20 +149,12 @@ class BuildViewModel( } if (isPluginProject) { - // The root project's build directory as the synced model has it, which - // relocated build output (ADFA-4930) moves out of the project folder. - val rootBuildDir = - IProjectManager - .getInstance() - .workspace - ?.rootProject - ?.buildDir - val cgpFile = - rootBuildDir?.let { withContext(Dispatchers.IO) { findPluginCgpFile(it, variant) } } + val workspace = IProjectManager.getInstance().workspace + val cgpFile = withContext(Dispatchers.IO) { findPluginCgpFile(workspace, variant.name) } if (cgpFile != null) { reporter.finish(BuildState.AwaitingPluginInstall(cgpFile)) } else { - log.warn("Plugin built successfully but no .cgp file under {}/plugin", rootBuildDir) + log.warn("Plugin built successfully but no .cgp file under {}/plugin", workspace?.rootProject?.buildDir) reporter.finish( BuildState.Error("Plugin built but output file (.cgp) not found"), ) @@ -327,18 +320,25 @@ class BuildViewModel( _buildState.value = BuildState.Idle } } +} - private fun findPluginCgpFile( - rootBuildDir: File, - variant: AndroidModels.AndroidVariant, - ): File? { - val pluginDir = File(rootBuildDir, "plugin") - if (!pluginDir.exists()) return null - - val isDebug = variant.name.contains("debug", ignoreCase = true) - return pluginDir - .listFiles { file -> file.extension.equals(PLUGIN_ARCHIVE_EXTENSION, ignoreCase = true) } - ?.filter { it.name.contains("-debug") == isDebug } - ?.maxByOrNull { it.lastModified() } - } +/** + * The newest `.cgp` a plugin build produced for [variantName], under the root project's build + * directory as the synced model has it: relocated build output (ADFA-4930) is not under + * `/build`, which may still hold a plugin from before the relocation. + * + * @return null when there is no model or no matching `.cgp`. + */ +internal fun findPluginCgpFile( + workspace: Workspace?, + variantName: String, +): File? { + val pluginDir = File(workspace?.rootProject?.buildDir ?: return null, "plugin") + if (!pluginDir.exists()) return null + + val isDebug = variantName.contains("debug", ignoreCase = true) + return pluginDir + .listFiles { file -> file.extension.equals(PLUGIN_ARCHIVE_EXTENSION, ignoreCase = true) } + ?.filter { it.name.contains("-debug") == isDebug } + ?.maxByOrNull { it.lastModified() } } diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt index 4c1bfc770a..b46b121d99 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/GradleQuickBuildProvisionerFakes.kt @@ -148,7 +148,7 @@ internal fun unsyncedProjectManager(projectRoot: File): FakeProjectManager = Fak internal fun androidModule( path: String = ":app", variantName: String? = "debug", - buildDir: File = File("app", "build"), + buildDir: File = File("/fake-project/app/build"), ): AndroidModule = mockk().also { module -> every { module.path } returns path @@ -224,7 +224,7 @@ internal fun writeSetupJson( entryActivity: String? = "com.example.demo.MainActivity", buildDir: File = File(moduleDir, "build"), ) { - val report = File(buildDir, QuickBuildTaskPaths.setupJson(variantName)) + val report = QuickBuildTaskPaths.setupJson(buildDir, variantName) report.parentFile.mkdirs() val apkPath = "app/build/outputs/apk/$variantName/app-$variantName.apk" report.writeText( @@ -241,7 +241,7 @@ internal fun writeUnparseableSetupJson( moduleDir: File, variantName: String = "debug", ) { - val report = File(moduleDir, "build/" + QuickBuildTaskPaths.setupJson(variantName)) + val report = QuickBuildTaskPaths.setupJson(File(moduleDir, "build"), variantName) report.parentFile.mkdirs() // A well-formed JSON object with no proxyAppId: parseable as JSON, unusable as a report, // which is the shape a schema drift actually produces. diff --git a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt index 418d2d89d2..d06f049d2b 100644 --- a/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/quickbuild/QuickBuildTaskPathsTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.quickbuild import com.google.common.truth.Truth.assertThat import org.junit.Test +import java.io.File /** * Two regressions are pinned here. @@ -76,15 +77,17 @@ class QuickBuildTaskPathsTest { // Both halves of the plugin contract: `/quickbuild//setup.json`. A // flavor-agnostic path here would read another flavor's report - the wrong APK and // the wrong applicationId. - assertThat(QuickBuildTaskPaths.setupJson("debug")) - .isEqualTo("quickbuild/debug/setup.json") - assertThat(QuickBuildTaskPaths.setupJson("demoDebug")) - .isEqualTo("quickbuild/demoDebug/setup.json") + val buildDir = File("/projects/app/build") + assertThat(QuickBuildTaskPaths.setupJson(buildDir, "debug")) + .isEqualTo(File(buildDir, "quickbuild/debug/setup.json")) + assertThat(QuickBuildTaskPaths.setupJson(buildDir, "demoDebug")) + .isEqualTo(File(buildDir, "quickbuild/demoDebug/setup.json")) } @Test fun `a blank variant reads the default variant's report`() { - assertThat(QuickBuildTaskPaths.setupJson("")).isEqualTo("quickbuild/debug/setup.json") - assertThat(QuickBuildTaskPaths.setupJson()).isEqualTo("quickbuild/debug/setup.json") + val buildDir = File("/projects/app/build") + assertThat(QuickBuildTaskPaths.setupJson(buildDir, "")).isEqualTo(File(buildDir, "quickbuild/debug/setup.json")) + assertThat(QuickBuildTaskPaths.setupJson(buildDir)).isEqualTo(File(buildDir, "quickbuild/debug/setup.json")) } } diff --git a/app/src/test/java/com/itsaky/androidide/viewmodel/PluginCgpLookupTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodel/PluginCgpLookupTest.kt new file mode 100644 index 0000000000..6895f9a6db --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/viewmodel/PluginCgpLookupTest.kt @@ -0,0 +1,60 @@ +package com.itsaky.androidide.viewmodel + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.projects.api.GradleProject +import com.itsaky.androidide.projects.api.Workspace +import io.mockk.every +import io.mockk.mockk +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +/** + * A plugin build's `.cgp` is found under the root project's build directory as the synced model + * has it. With relocated build output (ADFA-4930) that is in app storage, and `/build` + * may still hold a plugin from before the relocation. + */ +class PluginCgpLookupTest { + @get:Rule + val tmp = TemporaryFolder() + + private val project: File get() = File(tmp.root, "project") + + private val relocated: File get() = File(tmp.root, "no_backup/gradle-build/project-1234/main/root-5678") + + @Test + fun `the plugin is found under a relocated root build directory, not the project folder`() { + val stale = cgp(File(project, "build/plugin"), "old-debug.cgp") + val built = cgp(File(relocated, "plugin"), "myplugin-debug.cgp") + + assertThat(findPluginCgpFile(workspace(relocated), "debug")).isEqualTo(built) + assertThat(findPluginCgpFile(workspace(relocated), "debug")).isNotEqualTo(stale) + } + + @Test + fun `a release variant takes the plugin without the debug suffix`() { + cgp(File(relocated, "plugin"), "myplugin-debug.cgp") + val release = cgp(File(relocated, "plugin"), "myplugin.cgp") + + assertThat(findPluginCgpFile(workspace(relocated), "release")).isEqualTo(release) + } + + @Test + fun `nothing is found without a model or a plugin`() { + assertThat(findPluginCgpFile(null, "debug")).isNull() + assertThat(findPluginCgpFile(workspace(relocated), "debug")).isNull() + } + + private fun cgp( + dir: File, + name: String, + ): File = File(dir.apply { mkdirs() }, name).apply { writeText("cgp") } + + private fun workspace(rootBuildDir: File): Workspace { + val root = mockk() + every { root.buildDirPath } returns rootBuildDir.path + every { root.projectDirPath } returns project.path + return mockk().also { every { it.rootProject } returns root } + } +} From e0d1dc9c6c24a295524147726ee92824ef8c4e1c Mon Sep 17 00:00:00 2001 From: davidschachterADFA Date: Wed, 28 Oct 2026 18:37:57 -0700 Subject: [PATCH 3/3] ADFA-4930: delete relocated output with its project, sweep orphans, Export APK (#2151) * ADFA-4930: delete relocated build output with its project, sweep orphans Relocated build output outlived its project: deleting a project in the IDE left its tree in app storage, and so did deleting, moving or renaming it outside the IDE. - Deleting a project (Recents' delete and the Delete projects screen, both through RecentProjectsViewModel) deletes its trees. - At startup, off the main thread, a sweep deletes the trees of projects that no longer exist. A project on a volume that is not mounted is not gone, and a tree without a marker is left alone. Trees are matched by their project-path marker rather than by key, because deletion uses the canonical path and builds use projectDirPath; a symlinked spelling of the same project would key differently. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: Export APK from the editor toolbar With relocated build output the built APK is in app-private storage, where a file manager cannot reach it. A toolbar action, after Launch app and shown only while relocation is available (experiments), resolves the selected variant's APK from the synced model and offers: - Share: the share sheet, through the existing FileProvider. - Copy to Download: `-.apk`, numbered when taken, so an earlier export is never overwritten. Long-press help uses TooltipTag.EDITOR_TOOLBAR_EXPORT_APK ("project.export.apk"); its documentation.db text is a separate SQL script for OfflineDocumentationTools. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: plan doc matches PR 3's lifecycle and Export APK Docs only: where deletion hooks in, how trees are matched, what the sweep keeps, and that Export APK offers both the share sheet and a copy in Download. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: harden Export APK and tree deletion From the #2151 review: - A malformed or truncated APK listing no longer crashes Export; it reads as nothing to export. - Export refuses Quick Build's proxy APK, which Quick Build's build writes to the variant's output path: the APK is the proxy when the variant's setup.json names it and is not older than it. - A copy goes to a temporary name and is renamed into place, so one that fails part-way leaves no broken APK in Download. - Export is disabled during a user-visible build and refused, with a reason, while any build (Quick Build's prebuild included) runs. - The export name includes the module when the project has more than one app module. - A tree's marker is deleted last, so a deletion that stops part-way leaves a tree the next sweep can still identify. - The unsafe file-name rule is shared with ExternalFileInstallViewModel (no behaviour change there). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: sweep trees of projects deleted with their folder The startup sweep counted a project as gone only while its parent folder existed, so deleting a folder of projects in a file manager left every one of their trees in app storage until Clear storage. With the parent missing too, the nearest folder that exists now decides: a readable folder on a volume under /storage means the folders were deleted, while /storage itself means the project's volume is not mounted, and its tree is kept. Recents keeps its own rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: record the canonical project path in the marker A project opened through a symlinked root recorded the link in its tree's marker. Recents deletes the real folder, which leaves the link dangling, so the marker no longer canonicalized to the deleted project and delete-with-project missed the tree until the next startup sweep. The marker now holds the canonical path, the same spelling deletion compares against. Found by CodeRabbit on #2151. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 * ADFA-4930: delete output trees without following symlinks Hal Eisen on #2151: deleting a project's tree, and the startup sweep, used Kotlin's File.deleteRecursively, which follows a symlink to a directory and deletes what it points to. The trees live on ext4, where a build script, a CMake step or the terminal can leave such a link, so deleting a project could delete files outside its tree. The fix was in #2155 only (5d95f18), and this layer has to be safe to merge on its own. deleteTree now uses deleteWithoutFollowingLinks, the same file #2155 adds, and the sweep's listing of trees skips links (NOFOLLOW_LINKS), so a link in gradle-build/ is never treated as a tree. Each of the two new tests fails without its half of the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VKUthHVokuWKgP3ACLBii7 --------- Co-authored-by: Claude Opus 5.5 --- .../androidide/actions/etc/ExportApkAction.kt | 152 ++++++++++++++++++ .../CredentialProtectedApplicationLoader.kt | 8 + .../services/builder/BuildOutputLocation.kt | 102 +++++++++++- .../builder/DeleteWithoutFollowingLinks.kt | 59 +++++++ .../com/itsaky/androidide/utils/ApkExport.kt | 107 ++++++++++++ .../androidide/utils/EditorActivityActions.kt | 6 + .../com/itsaky/androidide/utils/FileNames.kt | 14 ++ .../viewmodel/RecentProjectsViewModel.kt | 9 ++ .../ExternalFileInstallViewModel.kt | 4 +- .../builder/BuildOutputLocationTest.kt | 149 ++++++++++++++++- .../itsaky/androidide/utils/ApkExportTest.kt | 142 ++++++++++++++++ ...6-10-14-adfa-4930-build-output-off-fuse.md | 6 +- .../androidide/idetooltips/TooltipTag.kt | 1 + resources/src/main/res/values/strings.xml | 8 + 14 files changed, 756 insertions(+), 11 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/actions/etc/ExportApkAction.kt create mode 100644 app/src/main/java/com/itsaky/androidide/services/builder/DeleteWithoutFollowingLinks.kt create mode 100644 app/src/main/java/com/itsaky/androidide/utils/ApkExport.kt create mode 100644 app/src/main/java/com/itsaky/androidide/utils/FileNames.kt create mode 100644 app/src/test/java/com/itsaky/androidide/utils/ApkExportTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/actions/etc/ExportApkAction.kt b/app/src/main/java/com/itsaky/androidide/actions/etc/ExportApkAction.kt new file mode 100644 index 0000000000..2924bfa6ed --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/actions/etc/ExportApkAction.kt @@ -0,0 +1,152 @@ +package com.itsaky.androidide.actions.etc + +import android.content.Context +import android.os.Environment +import android.view.MenuItem +import androidx.core.content.ContextCompat +import com.itsaky.androidide.R +import com.itsaky.androidide.actions.ActionData +import com.itsaky.androidide.actions.EditorActivityAction +import com.itsaky.androidide.actions.markInvisible +import com.itsaky.androidide.actions.openApplicationModuleChooser +import com.itsaky.androidide.activities.editor.EditorHandlerActivity +import com.itsaky.androidide.idetooltips.TooltipTag.EDITOR_TOOLBAR_EXPORT_APK +import com.itsaky.androidide.lookup.Lookup +import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.projects.builder.BuildService +import com.itsaky.androidide.projects.models.assembleTaskOutputListingFile +import com.itsaky.androidide.projects.models.buildDir +import com.itsaky.androidide.quickbuild.QuickBuildTaskPaths +import com.itsaky.androidide.utils.ApkExport +import com.itsaky.androidide.utils.DialogUtils +import com.itsaky.androidide.utils.IntentUtils +import com.itsaky.androidide.utils.flashError +import com.itsaky.androidide.utils.flashSuccess +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.slf4j.LoggerFactory +import java.io.File +import java.io.IOException + +/** + * Hands over the selected variant's built APK (ADFA-4930): with relocated build output it is in + * app-private storage, where a file manager cannot reach it. Offers the share sheet, or a copy in + * the Download folder. + */ +class ExportApkAction( + context: Context, + override val order: Int, +) : EditorActivityAction() { + override val id: String = "ide.editor.exportApk" + override var requiresUIThread: Boolean = true + + override fun retrieveTooltipTag(isReadOnlyContext: Boolean) = EDITOR_TOOLBAR_EXPORT_APK + + init { + label = context.getString(R.string.title_export_apk) + icon = ContextCompat.getDrawable(context, R.drawable.ic_share) + } + + override fun prepare(data: ActionData) { + super.prepare(data) + data.getActivity() ?: run { + markInvisible() + return + } + + visible = true + // The user-visible flag, like the build actions: Quick Build's prebuild after every project + // open is refused at the tap instead (isBuilding), with a reason. + enabled = + IProjectManager.getInstance().getAndroidAppModules().isNotEmpty() && + buildService()?.isUserVisibleBuildInProgress != true + } + + override suspend fun execAction(data: ActionData) { + if (isBuilding()) return + openApplicationModuleChooser(data) { app -> + val variant = app.getSelectedVariant() + if (variant == null) { + flashError(R.string.err_selected_variant_not_found) + return@openApplicationModuleChooser + } + + val activity = data.requireActivity() + val projectManager = IProjectManager.getInstance() + val projectDir = File(projectManager.projectDirPath) + // The module only when it tells two app modules' exports apart. + val module = app.name.takeIf { projectManager.getAndroidAppModules().size > 1 } + val name = listOfNotNull(projectDir.name, module, variant.name).joinToString("-") + activity.activityScope.launch { + val found = + withContext(Dispatchers.IO) { + ApkExport.resolve( + listingFile = variant.mainArtifact.assembleTaskOutputListingFile, + quickBuildReport = QuickBuildTaskPaths.setupJson(app.buildDir, variant.name), + projectDir = projectDir, + ) + } + when (found) { + ApkExport.Exportable.NotBuilt -> flashError(R.string.msg_export_apk_not_built) + ApkExport.Exportable.QuickBuildProxy -> flashError(R.string.msg_export_apk_quick_build) + is ApkExport.Exportable.Apk -> withContext(Dispatchers.Main) { offerExport(activity, found.file, name) } + } + } + } + } + + private fun buildService(): BuildService? = Lookup.getDefault().lookup(BuildService.KEY_BUILD_SERVICE) + + /** A build, Quick Build's prebuild included, may be rewriting the APK; refuse with a reason. */ + private fun isBuilding(): Boolean { + if (buildService()?.isBuildInProgress != true) return false + flashError(R.string.msg_export_apk_build_running) + return true + } + + private fun offerExport( + activity: EditorHandlerActivity, + apk: File, + name: String, + ) { + DialogUtils + .newMaterialDialogBuilder(activity) + .setTitle(R.string.title_export_apk) + .setItems( + arrayOf( + activity.getString(R.string.export_apk_share), + activity.getString(R.string.export_apk_copy_to_download), + ), + ) { _, which -> + if (which == 0) { + IntentUtils.shareFile(activity, apk, ApkExport.MIME_TYPE) + } else if (!isBuilding()) { + activity.activityScope.launch(Dispatchers.IO) { copyToDownload(activity, apk, name) } + } + }.setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun copyToDownload( + activity: EditorHandlerActivity, + apk: File, + name: String, + ) { + @Suppress("DEPRECATION") + val download = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + try { + val copy = ApkExport.copyTo(apk, download, name) + flashSuccess(activity.getString(R.string.msg_export_apk_saved, copy.name)) + } catch (e: IOException) { + log.error("Cannot copy {} to {}", apk, download, e) + flashError(R.string.msg_export_apk_failed) + } + } + + override fun getShowAsActionFlags(data: ActionData): Int = MenuItem.SHOW_AS_ACTION_IF_ROOM + + companion object { + private val log = LoggerFactory.getLogger(ExportApkAction::class.java) + } +} diff --git a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt index eeac14fa2e..82f0d511ce 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -27,6 +27,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl import com.itsaky.androidide.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.resources.localization.LocaleProvider +import com.itsaky.androidide.services.builder.BuildOutputLocation import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult import com.itsaky.androidide.ui.themes.IDETheme import com.itsaky.androidide.ui.themes.IThemeManager @@ -142,6 +143,13 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { IDEColorSchemeProvider.init() } + app.coroutineScope.launch(Dispatchers.IO) { + // ADFA-4930: relocated build output of projects deleted, moved or renamed outside + // the IDE. + val removed = BuildOutputLocation.sweep(app.noBackupFilesDir) + if (removed > 0) logger.info("Swept {} orphaned build output tree(s)", removed) + } + if (!VMUtils.isJvm || VMUtils.isInstrumentedTest) { ToolsManager.init(app, null) } diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/BuildOutputLocation.kt b/app/src/main/java/com/itsaky/androidide/services/builder/BuildOutputLocation.kt index 6b0e7a3291..794834c6df 100644 --- a/app/src/main/java/com/itsaky/androidide/services/builder/BuildOutputLocation.kt +++ b/app/src/main/java/com/itsaky/androidide/services/builder/BuildOutputLocation.kt @@ -8,8 +8,12 @@ import com.itsaky.androidide.tooling.api.GradlePluginConfig.PROPERTY_BUILD_OUTPU import com.itsaky.androidide.utils.Experiment import com.itsaky.androidide.utils.Experiments import com.itsaky.androidide.utils.ProjectStorageKey +import com.itsaky.androidide.utils.canonicalProjectLocation +import com.itsaky.androidide.utils.isDeletedProjectDirectory import java.io.File import java.io.IOException +import java.nio.file.Files +import java.nio.file.LinkOption /** * Where a project's Gradle build output goes when it is moved off the FUSE-backed project folder @@ -26,7 +30,7 @@ object BuildOutputLocation { /** Parent of every project's tree, under `noBackupFilesDir`. */ const val DIR_NAME = "gradle-build" - /** Holds the project's path, so a sweep can find trees whose project is gone. */ + /** Holds the project's canonical path, so a sweep can find trees whose project is gone. */ const val PROJECT_PATH_FILE = "project-path" private const val KOTLIN_PERSISTENT_DIR = "kotlin.project.persistent.dir" @@ -34,6 +38,9 @@ object BuildOutputLocation { private const val NO_WATCH_FS = "--no-watch-fs" private const val PROJECT_CACHE_DIR = "--project-cache-dir" + /** Where Android mounts storage volumes: internal storage, and each SD card or USB drive. */ + private val STORAGE_ROOT = File("/storage") + /** Whether the switch exists at all: early access only (EXPERIMENTS.md). */ fun isAvailable(): Boolean = Experiments.isOn(Experiment.BUILD_OUTPUT_RELOCATION) @@ -77,7 +84,8 @@ object BuildOutputLocation { fun withoutWatchConflict(args: List): List = if (PROJECT_CACHE_DIR in args) args.filterNot { it == WATCH_FS } else args /** - * Creates [tree] and records [projectDir] in it. + * Creates [tree] and records [projectDir] in it, canonically: a project deleted through its real + * path must still match a marker written while it was opened through a symlink. * * @return false when [tree] or its marker cannot be written; a sync then keeps output in the * project folder. @@ -88,7 +96,7 @@ object BuildOutputLocation { ): Boolean { if (!tree.isDirectory && !tree.mkdirs()) return false val marker = File(tree, PROJECT_PATH_FILE) - val path = projectDir.absolutePath + val path = projectDir.canonicalProjectLocation() return try { if (!marker.isFile || marker.readText() != path) marker.writeText(path) true @@ -97,6 +105,94 @@ object BuildOutputLocation { } } + /** + * Deletes the trees of [projectDir], matched by their [PROJECT_PATH_FILE] marker rather than by + * key, so a path spelled differently (`/sdcard` against `/storage/emulated/0`) still matches. + * Call it when the user deletes the project. + * + * @return how many trees were deleted. + */ + fun removeTreesOf( + noBackupDir: File, + projectDir: File, + ): Int { + val location = projectDir.canonicalProjectLocation() + return deleteTreesWhere(noBackupDir) { it.canonicalProjectLocation() == location } + } + + /** + * Deletes the trees of projects that no longer exist, such as a project deleted, moved or renamed + * outside the IDE, or deleted with the folder holding it. A project on a volume that is not + * mounted is not gone, and a tree without a marker is left alone. Runs on a background thread at + * startup. + * + * @param volumesRoot where storage volumes are mounted; tests pass their own. + * @return how many trees were deleted. + */ + fun sweep( + noBackupDir: File, + volumesRoot: File = STORAGE_ROOT, + ): Int = deleteTreesWhere(noBackupDir) { isGone(it, volumesRoot) } + + /** + * Whether [project] was deleted. With its parent folder still there, Recents' rule decides. With + * the parent missing too, the nearest folder that exists decides: a readable folder on a volume + * means the folders were deleted, while [volumesRoot] itself means the volume is not mounted. + */ + private fun isGone( + project: File, + volumesRoot: File, + ): Boolean { + if (project.isDeletedProjectDirectory()) return true + if (project.exists()) return false + val nearest = generateSequence(project.parentFile) { it.parentFile }.firstOrNull { it.exists() } ?: return false + return try { + val ancestor = nearest.canonicalFile + val root = volumesRoot.canonicalFile + ancestor != root && ancestor.startsWith(root) && ancestor.isDirectory && ancestor.canRead() + } catch (e: IOException) { + false + } + } + + private fun deleteTreesWhere( + noBackupDir: File, + isOrphan: (File) -> Boolean, + ): Int { + // A link among the trees is not a tree; following it would delete what it points to. + val trees = + File(noBackupDir, DIR_NAME).listFiles { file -> Files.isDirectory(file.toPath(), LinkOption.NOFOLLOW_LINKS) } + ?: return 0 + return trees.count { tree -> + val project = projectOf(tree) + project != null && isOrphan(project) && deleteTree(tree) + } + } + + /** + * Deletes [tree] with its marker last: a deletion that stops part-way keeps the marker, so the + * next sweep can still tell whose tree it is and finish the job. A build can leave symlinks in its + * output, so the deletion never follows one out of the tree. + */ + private fun deleteTree(tree: File): Boolean { + val marker = File(tree, PROJECT_PATH_FILE) + val contents = tree.listFiles() ?: return false + val deleted = contents.filter { it != marker }.map { deleteWithoutFollowingLinks(it) }.all { it } + return deleted && (!marker.exists() || marker.delete()) && tree.delete() + } + + /** The project [tree] belongs to, from its marker, or null when the marker is missing or unreadable. */ + private fun projectOf(tree: File): File? = + try { + File(tree, PROJECT_PATH_FILE) + .takeIf { it.isFile } + ?.readText() + ?.takeIf { it.isNotBlank() } + ?.let(::File) + } catch (e: IOException) { + null + } + /** * Whether a synced model's build directory lies in [tree], meaning the sync that produced the * model relocated that project's build output. diff --git a/app/src/main/java/com/itsaky/androidide/services/builder/DeleteWithoutFollowingLinks.kt b/app/src/main/java/com/itsaky/androidide/services/builder/DeleteWithoutFollowingLinks.kt new file mode 100644 index 0000000000..9490681da0 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/services/builder/DeleteWithoutFollowingLinks.kt @@ -0,0 +1,59 @@ +package com.itsaky.androidide.services.builder + +import java.io.File +import java.io.IOException +import java.nio.file.FileVisitResult +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes + +/** + * Deletes [dir] and everything in it without following symlinks, so a link inside never leads the + * deletion out of [dir]. A file that cannot be deleted is skipped, not fatal. + * + * @return whether [dir] is gone. + */ +internal fun deleteWithoutFollowingLinks(dir: File): Boolean { + val start = dir.toPath() + if (Files.notExists(start, LinkOption.NOFOLLOW_LINKS)) return true + try { + Files.walkFileTree( + start, + object : SimpleFileVisitor() { + override fun visitFile( + file: Path, + attrs: BasicFileAttributes, + ): FileVisitResult { + deleteQuietly(file) + return FileVisitResult.CONTINUE + } + + override fun visitFileFailed( + file: Path, + exc: IOException, + ): FileVisitResult = FileVisitResult.CONTINUE + + override fun postVisitDirectory( + dir: Path, + exc: IOException?, + ): FileVisitResult { + deleteQuietly(dir) + return FileVisitResult.CONTINUE + } + }, + ) + } catch (e: IOException) { + return false + } + return Files.notExists(start, LinkOption.NOFOLLOW_LINKS) +} + +private fun deleteQuietly(path: Path) { + try { + Files.deleteIfExists(path) + } catch (e: IOException) { + // Left in place; the folder holding it stays too. + } +} diff --git a/app/src/main/java/com/itsaky/androidide/utils/ApkExport.kt b/app/src/main/java/com/itsaky/androidide/utils/ApkExport.kt new file mode 100644 index 0000000000..c420c8f5a1 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/utils/ApkExport.kt @@ -0,0 +1,107 @@ +package com.itsaky.androidide.utils + +import com.itsaky.androidide.models.ApkMetadata +import org.appdevforall.cotg.quickbuild.data.ProxyAppInfo +import org.slf4j.LoggerFactory +import java.io.File +import java.io.IOException + +/** Finds a built APK and copies it out of app storage under a readable name (ADFA-4930). */ +internal object ApkExport { + const val MIME_TYPE = "application/vnd.android.package-archive" + + private val log = LoggerFactory.getLogger(ApkExport::class.java) + + /** What [resolve] found to export. */ + sealed interface Exportable { + data class Apk( + val file: File, + ) : Exportable + + /** No APK yet, or its listing cannot be read. */ + data object NotBuilt : Exportable + + /** + * The APK at the variant's output path is Quick Build's live-reload proxy app, which its + * build writes there; exporting it would hand over the wrong app. + */ + data object QuickBuildProxy : Exportable + } + + /** + * @param listingFile the variant's APK listing file, from the synced model. + * @param quickBuildReport the variant's Quick Build `setup.json`, which names the proxy APK. + * @param projectDir the project's root, which the report's relative paths resolve against. + */ + fun resolve( + listingFile: File, + quickBuildReport: File, + projectDir: File, + ): Exportable { + val apk = + try { + ApkMetadata.findApkFile(listingFile)?.takeIf { it.isFile } + } catch (e: Exception) { + // A truncated or malformed listing (JSON or redirect) means there is no APK to trust. + log.warn("Cannot read the APK listing {}", listingFile, e) + null + } ?: return Exportable.NotBuilt + return if (isQuickBuildProxy(apk, quickBuildReport, projectDir)) Exportable.QuickBuildProxy else Exportable.Apk(apk) + } + + /** + * Quick Build's report is written after the proxy APK it names, so the APK is the proxy when + * the report names it and is not older than it. A standard build rewrites the APK and leaves + * the report alone, so after one the APK is newer. + */ + private fun isQuickBuildProxy( + apk: File, + report: File, + projectDir: File, + ): Boolean { + if (!report.isFile) return false + val reported = + try { + ProxyAppInfo.parse(report.readText(), projectDir)?.apk + } catch (e: IOException) { + null + } ?: return false + return reported.absoluteFile.normalize() == apk.absoluteFile.normalize() && report.lastModified() >= apk.lastModified() + } + + /** + * Copies [apk] into [dir] as `.apk`, or ` (2).apk` and so on when that is taken, so + * an earlier export is never overwritten. The copy goes to a temporary name first, so one that + * fails part-way never leaves a broken APK under the export's name. + * + * @param name the file name without `.apk`; characters a file name cannot hold are replaced. + * @return the copy. + * @throws IOException when [dir] cannot be created or the copy fails. + */ + fun copyTo( + apk: File, + dir: File, + name: String, + copy: (File, File) -> Unit = { from, to -> from.copyTo(to) }, + ): File { + if (!dir.isDirectory && !dir.mkdirs()) throw IOException("Cannot create $dir") + val target = freeTarget(dir, safeFileName(name, "app")) + val partial = File(dir, ".${target.name}.partial") + try { + partial.delete() + copy(apk, partial) + if (!partial.renameTo(target)) throw IOException("Cannot rename $partial to $target") + } finally { + partial.delete() + } + return target + } + + private fun freeTarget( + dir: File, + name: String, + ): File = + generateSequence(1) { it + 1 } + .map { n -> File(dir, if (n == 1) "$name.apk" else "$name ($n).apk") } + .first { !it.exists() } +} diff --git a/app/src/main/java/com/itsaky/androidide/utils/EditorActivityActions.kt b/app/src/main/java/com/itsaky/androidide/utils/EditorActivityActions.kt index 2ac9699f3b..cc037930d9 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/EditorActivityActions.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/EditorActivityActions.kt @@ -38,6 +38,7 @@ import com.itsaky.androidide.actions.editor.LongSelectAction import com.itsaky.androidide.actions.editor.PasteAction import com.itsaky.androidide.actions.editor.SelectAllAction import com.itsaky.androidide.actions.etc.DisconnectLogSendersAction +import com.itsaky.androidide.actions.etc.ExportApkAction import com.itsaky.androidide.actions.etc.FindAction import com.itsaky.androidide.actions.etc.FindInFileAction import com.itsaky.androidide.actions.etc.FindInProjectAction @@ -64,6 +65,7 @@ import com.itsaky.androidide.actions.text.UndoAction import com.itsaky.androidide.plugins.extensions.UIExtension import com.itsaky.androidide.plugins.manager.build.PluginBuildActionManager import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.services.builder.BuildOutputLocation /** * Takes care of registering actions to the actions registry for the editor activity. @@ -106,6 +108,10 @@ class EditorActivityActions { registry.registerAction(FindInProjectAction(context, order++)) registry.registerAction(ReplaceInProjectAction(context, order++)) registry.registerAction(LaunchAppAction(context, order++)) + // ADFA-4930: relocated build output keeps the APK out of the project folder. + if (BuildOutputLocation.isAvailable()) { + registry.registerAction(ExportApkAction(context, order++)) + } registry.registerAction(DisconnectLogSendersAction(context, order++)) // Plugin contributions diff --git a/app/src/main/java/com/itsaky/androidide/utils/FileNames.kt b/app/src/main/java/com/itsaky/androidide/utils/FileNames.kt new file mode 100644 index 0000000000..410d9358dd --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/utils/FileNames.kt @@ -0,0 +1,14 @@ +package com.itsaky.androidide.utils + +/** Characters a file name on shared storage cannot hold. */ +internal val UNSAFE_FILENAME_CHARS = Regex("[\\\\/:*?\"<>|]") + +/** + * [raw] with every character a file name cannot hold replaced by `_`, and trimmed. + * + * @param fallback the name to use when nothing is left. + */ +internal fun safeFileName( + raw: String, + fallback: String, +): String = raw.replace(UNSAFE_FILENAME_CHARS, "_").trim().ifBlank { fallback } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/RecentProjectsViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/RecentProjectsViewModel.kt index 1436c3079a..84f398345f 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/RecentProjectsViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/RecentProjectsViewModel.kt @@ -15,6 +15,7 @@ import com.itsaky.androidide.roomData.recentproject.RecentProject import com.itsaky.androidide.roomData.recentproject.RecentProjectDao import com.itsaky.androidide.roomData.recentproject.RecentProjectMaintenance import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase +import com.itsaky.androidide.services.builder.BuildOutputLocation import com.itsaky.androidide.templates.Language import com.itsaky.androidide.utils.canonicalProjectLocation import com.itsaky.androidide.utils.getCreatedTime @@ -284,6 +285,12 @@ class RecentProjectsViewModel( } } + /** ADFA-4930: the project's relocated build output goes with it. Call on [Dispatchers.IO]. */ + private fun removeBuildOutput(location: String) { + val removed = BuildOutputLocation.removeTreesOf(getApplication().noBackupFilesDir, File(location)) + if (removed > 0) logger.info("Deleted {} build output tree(s) of {}", removed, location) + } + fun deleteProjectByLocation(location: String) = viewModelScope.launch { try { @@ -297,6 +304,7 @@ class RecentProjectsViewModel( if (isDeleted) { recentProjectDao.deleteByLocation(projectToDelete.location) + removeBuildOutput(projectToDelete.location) } projectToDelete.takeIf { isDeleted } } @@ -394,6 +402,7 @@ class RecentProjectsViewModel( if (isDeletedFromStorage) { successfullyDeletedLocations.add(project.location) + removeBuildOutput(project.location) } else { logger.warn("Failed to delete project files from storage: ${project.location}") allDeletionsSucceeded = false diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt index f2bb0c6dc3..1b238ff2d8 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt @@ -13,6 +13,7 @@ import com.itsaky.androidide.ui.models.ExternalFileInstallUiEvent import com.itsaky.androidide.utils.InstallTempFiles import com.itsaky.androidide.utils.LastValueGate import com.itsaky.androidide.utils.UriFileImporter +import com.itsaky.androidide.utils.safeFileName import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable @@ -41,7 +42,6 @@ class ExternalFileInstallViewModel( ) : ViewModel() { private companion object { private val log = LoggerFactory.getLogger(ExternalFileInstallViewModel::class.java) - private val UNSAFE_FILENAME_CHARS = Regex("[\\\\/:*?\"<>|]") // A cold OS-triggered launch of this activity can win the race against IDEApplication's // async setup (device-unlock -> CredentialProtectedApplicationLoader.load(), which itself @@ -345,7 +345,7 @@ class ExternalFileInstallViewModel( return candidate } - fun sanitizeBaseName(rawName: String): String = rawName.replace(UNSAFE_FILENAME_CHARS, "_").trim().ifBlank { "templates" } + fun sanitizeBaseName(rawName: String): String = safeFileName(rawName, "templates") private suspend fun sendErrorAndFinish( generation: Int, diff --git a/app/src/test/java/com/itsaky/androidide/services/builder/BuildOutputLocationTest.kt b/app/src/test/java/com/itsaky/androidide/services/builder/BuildOutputLocationTest.kt index b63acc1597..cb14c2d744 100644 --- a/app/src/test/java/com/itsaky/androidide/services/builder/BuildOutputLocationTest.kt +++ b/app/src/test/java/com/itsaky/androidide/services/builder/BuildOutputLocationTest.kt @@ -11,6 +11,7 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File +import java.nio.file.Files class BuildOutputLocationTest { @get:Rule @@ -58,14 +59,14 @@ class BuildOutputLocationTest { } @Test - fun `prepare creates the tree and records the project path`() { + fun `prepare creates the tree and records the canonical project path`() { val tree = File(tmp.root, "gradle-build/app-1234") val project = File(tmp.root, "projects/app") assertThat(BuildOutputLocation.prepare(tree, project)).isTrue() assertThat(tree.isDirectory).isTrue() - assertThat(File(tree, BuildOutputLocation.PROJECT_PATH_FILE).readText()).isEqualTo(project.absolutePath) + assertThat(File(tree, BuildOutputLocation.PROJECT_PATH_FILE).readText()).isEqualTo(project.canonicalPath) } @Test @@ -76,7 +77,7 @@ class BuildOutputLocationTest { assertThat(BuildOutputLocation.prepare(tree, project)).isTrue() - assertThat(File(tree, BuildOutputLocation.PROJECT_PATH_FILE).readText()).isEqualTo(project.absolutePath) + assertThat(File(tree, BuildOutputLocation.PROJECT_PATH_FILE).readText()).isEqualTo(project.canonicalPath) } @Test @@ -154,6 +155,148 @@ class BuildOutputLocationTest { assertThat(BuildOutputLocation.syncPending(modelRelocated = null, requested = true)).isFalse() } + @Test + fun `deleting a project deletes its tree and no other`() { + val noBackup = tmp.newFolder("no_backup") + val app = tmp.newFolder("projects", "app") + val other = tmp.newFolder("projects", "other") + val appTree = treeOf(noBackup, app) + val otherTree = treeOf(noBackup, other) + + assertThat(BuildOutputLocation.removeTreesOf(noBackup, app)).isEqualTo(1) + + assertThat(appTree.exists()).isFalse() + assertThat(otherTree.isDirectory).isTrue() + } + + @Test + fun `deleting a project's tree never follows a symlink out of it`() { + val noBackup = tmp.newFolder("no_backup") + val project = tmp.newFolder("projects", "app") + val tree = treeOf(noBackup, project) + val elsewhere = tmp.newFolder("elsewhere") + val precious = File(elsewhere, "precious.txt").apply { writeText("keep me") } + // A build can leave a link in its output, such as one a custom task makes. + Files.createSymbolicLink(File(tree, "main/app-1234/outputs/link").toPath(), elsewhere.toPath()) + + assertThat(BuildOutputLocation.removeTreesOf(noBackup, project)).isEqualTo(1) + + assertThat(tree.exists()).isFalse() + assertThat(precious.readText()).isEqualTo("keep me") + } + + @Test + fun `the sweep does not follow a link among the trees`() { + val noBackup = tmp.newFolder("no_backup") + // A folder outside gradle-build whose marker names a deleted project, reached through a link. + val elsewhere = tmp.newFolder("elsewhere") + File(elsewhere, BuildOutputLocation.PROJECT_PATH_FILE).writeText(File(tmp.newFolder("projects"), "gone").path) + val precious = File(elsewhere, "precious.txt").apply { writeText("keep me") } + Files.createSymbolicLink(File(File(noBackup, BuildOutputLocation.DIR_NAME).apply { mkdirs() }, "link").toPath(), elsewhere.toPath()) + + assertThat(BuildOutputLocation.sweep(noBackup, tmp.root)).isEqualTo(0) + + assertThat(precious.readText()).isEqualTo("keep me") + } + + @Test + fun `a tree recorded under another spelling of the project path is still found`() { + val noBackup = tmp.newFolder("no_backup") + val app = tmp.newFolder("storage", "app") + val link = File(tmp.root, "sdcard").toPath() + Files.createSymbolicLink(link, app.parentFile.toPath()) + val tree = treeOf(noBackup, app) + // A marker written before the canonical path was recorded holds the alias spelling. + File(tree, BuildOutputLocation.PROJECT_PATH_FILE).writeText(File(link.toFile(), "app").path) + + assertThat(BuildOutputLocation.removeTreesOf(noBackup, app)).isEqualTo(1) + assertThat(tree.exists()).isFalse() + } + + @Test + fun `deleting a project opened through a symlinked root deletes its tree`() { + val noBackup = tmp.newFolder("no_backup") + val real = tmp.newFolder("real", "app") + val alias = File(tmp.root, "alias-app").also { Files.createSymbolicLink(it.toPath(), real.toPath()) } + val tree = treeOf(noBackup, alias) + // Recents deletes the real folder, which leaves the alias dangling. + real.deleteRecursively() + + assertThat(BuildOutputLocation.removeTreesOf(noBackup, real)).isEqualTo(1) + assertThat(tree.exists()).isFalse() + } + + @Test + fun `the sweep deletes the trees of deleted projects only`() { + val noBackup = tmp.newFolder("no_backup") + val kept = tmp.newFolder("projects", "kept") + val deleted = tmp.newFolder("projects", "deleted") + val keptTree = treeOf(noBackup, kept) + val deletedTree = treeOf(noBackup, deleted) + val volumes = tmp.newFolder("storage") + val unmountedTree = treeOf(noBackup, File(volumes, "usb-drive/Projects/app")) + val markerless = File(noBackup, "${BuildOutputLocation.DIR_NAME}/no-marker").apply { mkdirs() } + deleted.deleteRecursively() + + assertThat(BuildOutputLocation.sweep(noBackup, volumes)).isEqualTo(1) + + assertThat(deletedTree.exists()).isFalse() + assertThat(keptTree.isDirectory).isTrue() + // Only the volumes root is left of the path: the volume is not mounted, not deleted. + assertThat(unmountedTree.isDirectory).isTrue() + assertThat(markerless.isDirectory).isTrue() + } + + @Test + fun `the sweep deletes the trees of projects deleted with their folder`() { + val noBackup = tmp.newFolder("no_backup") + val volumes = tmp.newFolder("storage") + val experiments = tmp.newFolder("storage", "emulated", "Projects", "Experiments") + val first = treeOf(noBackup, File(experiments, "first").apply { mkdirs() }) + val second = treeOf(noBackup, File(experiments, "nested/second").apply { mkdirs() }) + val outsideVolumes = treeOf(noBackup, File(tmp.root, "elsewhere/gone/app")) + experiments.deleteRecursively() + + assertThat(BuildOutputLocation.sweep(noBackup, volumes)).isEqualTo(2) + + assertThat(first.exists()).isFalse() + assertThat(second.exists()).isFalse() + // Off the volumes, a missing parent proves nothing, so the tree stays. + assertThat(outsideVolumes.isDirectory).isTrue() + } + + @Test + fun `a deletion that stops part-way keeps the marker for the next sweep`() { + val noBackup = tmp.newFolder("no_backup") + val project = tmp.newFolder("projects", "app") + val tree = treeOf(noBackup, project) + val locked = File(tree, "main/app-1234/outputs").apply { File(this, "app-debug.apk").writeText("apk") } + locked.setWritable(false) + try { + assertThat(BuildOutputLocation.removeTreesOf(noBackup, project)).isEqualTo(0) + + assertThat(File(tree, BuildOutputLocation.PROJECT_PATH_FILE).isFile).isTrue() + } finally { + locked.setWritable(true) + } + assertThat(BuildOutputLocation.removeTreesOf(noBackup, project)).isEqualTo(1) + assertThat(tree.exists()).isFalse() + } + + @Test + fun `the sweep copes with no trees at all`() { + assertThat(BuildOutputLocation.sweep(tmp.newFolder("no_backup"))).isEqualTo(0) + } + + private fun treeOf( + noBackup: File, + project: File, + ): File = + BuildOutputLocation.treeFor(noBackup, project).also { + assertThat(BuildOutputLocation.prepare(it, project)).isTrue() + File(it, "main/app-1234/outputs").mkdirs() + } + private fun workspace( rootBuildDir: File, vararg subprojectBuildDirs: File, diff --git a/app/src/test/java/com/itsaky/androidide/utils/ApkExportTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ApkExportTest.kt new file mode 100644 index 0000000000..b58c2be3a4 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/utils/ApkExportTest.kt @@ -0,0 +1,142 @@ +package com.itsaky.androidide.utils + +import com.google.common.truth.Truth.assertThat +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.io.IOException + +class ApkExportTest { + @get:Rule + val tmp = TemporaryFolder() + + private val apk: File get() = + File(tmp.root, "tree/app-debug.apk").apply { + parentFile.mkdirs() + writeText("apk") + } + + @Test + fun `no listing means nothing to export`() { + assertThat(ApkExport.resolve(File(tmp.root, "out/output-metadata.json"), report(), tmp.root)) + .isEqualTo(ApkExport.Exportable.NotBuilt) + } + + @Test + fun `a malformed listing is nothing to export, not a crash`() { + val listing = File(tmp.newFolder("out"), "output-metadata.json").apply { writeText("{\"elements\": [") } + + assertThat(ApkExport.resolve(listing, report(), tmp.root)).isEqualTo(ApkExport.Exportable.NotBuilt) + } + + @Test + fun `a standard build's APK is exported`() { + val (listing, built) = built() + + assertThat(ApkExport.resolve(listing, report(), tmp.root)).isEqualTo(ApkExport.Exportable.Apk(built)) + } + + @Test + fun `Quick Build's proxy APK at the same path is refused`() { + val (listing, built) = built() + val report = report(names = built, at = built.lastModified() + 1_000) + + assertThat(ApkExport.resolve(listing, report, tmp.root)).isEqualTo(ApkExport.Exportable.QuickBuildProxy) + } + + @Test + fun `a standard build after Quick Build's makes the APK exportable again`() { + val (listing, built) = built() + val report = report(names = built, at = built.lastModified() - 1_000) + + assertThat(ApkExport.resolve(listing, report, tmp.root)).isEqualTo(ApkExport.Exportable.Apk(built)) + } + + @Test + fun `a copy that fails part-way leaves nothing under the export's name`() { + val download = tmp.newFolder("Download") + + try { + ApkExport.copyTo(apk, download, "app-debug") { _, to -> + to.writeText("half an ap") + throw IOException("disk full") + } + } catch (e: IOException) { + // expected + } + + assertThat(download.list()).isEmpty() + } + + /** A variant's output directory holding `app-debug.apk` and its listing. */ + private fun built(): Pair { + val dir = tmp.newFolder("outputs", "apk", "debug") + val apk = File(dir, "app-debug.apk").apply { writeText("apk") } + val listing = + File(dir, "output-metadata.json").apply { + writeText( + """{"version":3,"artifactType":{"type":"APK","kind":"Directory"},"applicationId":"com.example.app",""" + + """"variantName":"debug","elements":[{"type":"SINGLE","outputFile":"app-debug.apk"}],"elementType":"File"}""", + ) + } + return listing to apk + } + + /** Quick Build's report, naming [names] as its proxy APK, written at [at]; absent without [names]. */ + private fun report( + names: File? = null, + at: Long = 0, + ): File { + val report = File(tmp.root, "quickbuild/debug/setup.json") + if (names != null) { + report.parentFile.mkdirs() + report.writeText("""{"proxyAppId":"com.example.app","entryActivity":null,"apk":"${names.absolutePath}"}""") + report.setLastModified(at) + } + return report + } + + @Test + fun `the copy is named after the project and variant`() { + val download = tmp.newFolder("Download") + + val copy = ApkExport.copyTo(apk, download, "My Application-debug") + + assertThat(copy).isEqualTo(File(download, "My Application-debug.apk")) + assertThat(copy.readText()).isEqualTo("apk") + } + + @Test + fun `an earlier export is never overwritten`() { + val download = tmp.newFolder("Download") + File(download, "app-debug.apk").writeText("first") + File(download, "app-debug (2).apk").writeText("second") + + val copy = ApkExport.copyTo(apk, download, "app-debug") + + assertThat(copy.name).isEqualTo("app-debug (3).apk") + assertThat(File(download, "app-debug.apk").readText()).isEqualTo("first") + } + + @Test + fun `characters a file name cannot hold are replaced`() { + val copy = ApkExport.copyTo(apk, tmp.newFolder("Download"), "a/b:c-debug") + + assertThat(copy.name).isEqualTo("a_b_c-debug.apk") + } + + @Test + fun `a missing Download folder is created`() { + val download = File(tmp.root, "sdcard/Download") + + assertThat(ApkExport.copyTo(apk, download, "app-debug").isFile).isTrue() + } + + @Test(expected = IOException::class) + fun `a Download folder that cannot be created is reported`() { + val blocker = tmp.newFile("sdcard") + + ApkExport.copyTo(apk, File(blocker, "Download"), "app-debug") + } +} diff --git a/docs/superpowers/plans/2026-10-14-adfa-4930-build-output-off-fuse.md b/docs/superpowers/plans/2026-10-14-adfa-4930-build-output-off-fuse.md index f966a1091d..a50ae4798c 100644 --- a/docs/superpowers/plans/2026-10-14-adfa-4930-build-output-off-fuse.md +++ b/docs/superpowers/plans/2026-10-14-adfa-4930-build-output-off-fuse.md @@ -66,8 +66,8 @@ Measured 2026-10-14 with the IDE's Gradle arguments, same template project on bo ### Lifecycle -- **Project deleted in the IDE** (`RecentProjectsAdapter.kt:213`, `DeleteProjectFragment`): delete its output tree too. -- **Orphans** (project moved, renamed or deleted outside the IDE): at startup, off the main thread, remove trees whose `project-path` marker no longer exists - the same shape as `QuickBuildScratch.sweep`. +- **Project deleted in the IDE**: both deletion paths (Recents and the Delete projects screen) go through `RecentProjectsViewModel`, which deletes the project's trees too. Trees are matched by their `project-path` marker, not by key: deletion uses the canonical path and builds use `projectDirPath`, so a symlinked spelling would key differently. +- **Orphans** (project moved, renamed or deleted outside the IDE): at startup, off the main thread, remove trees whose project no longer exists. A project counts as gone when its parent folder exists, or, with the parent deleted too, when the nearest folder that exists is a readable folder on a volume under `/storage`. A volume that is not mounted leaves only `/storage` itself, so it doesn't count. Trees without a marker are left alone. Unlike `QuickBuildScratch.sweep`, which clears every tree, this keeps the output of live projects. - **Existing `build/` folders in projects**: leave them. They go stale but do no harm. A later "free space" action can offer to remove them. - **Storage**: output now counts as app data in Settings, and "Clear storage" removes it (the next build is a full one). Uninstalling removes it as well; sources are unaffected. @@ -75,7 +75,7 @@ Measured 2026-10-14 with the IDE's Gradle arguments, same template project on bo These are the tradeoffs from the original analysis, with how this plan handles each: -- **The APK is no longer in the project folder**, file manager or MTP. Add an **Export APK** action that copies the built APK to `Download/` or opens the share sheet. The survey found no existing export or share action. +- **The APK is no longer in the project folder**, file manager or MTP. Add an **Export APK** toolbar action, shown while relocation is available, that offers the share sheet or a copy in `Download/` (`[project]-[variant].apk`, numbered when taken). The survey found no existing export action. - **Build output no longer travels with a copied project folder.** That's acceptable: it can be rebuilt, and copying `build/` is rarely wanted. - **Terminal builds** (`./gradlew` in the IDE's terminal) don't get the redirect, so they still build into the project folder, separately from the IDE's tree. Document this. Changing it is a follow-up if users trip over it. diff --git a/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt b/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt index 202c545561..5d58809319 100644 --- a/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt +++ b/idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt @@ -225,6 +225,7 @@ object TooltipTag { const val EDITOR_TOOLBAR_FIND_IN_FILE = "editor.find.in.file" const val EDITOR_TOOLBAR_SYNC = "project.sync" const val EDITOR_TOOLBAR_LAUNCH_APP = "project.launch.app" + const val EDITOR_TOOLBAR_EXPORT_APK = "project.export.apk" const val EDITOR_TOOLBAR_UNDO = "editor.undo" const val EDITOR_TOOLBAR_REDO = "editor.redo" const val EDITOR_TOOLBAR_QUICK_SAVE = "project.save" diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index bfd9f60bb6..aaf7c23446 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -879,6 +879,14 @@ Cannot run application. Unable to determine package name. Cannot run application. No application modules found in project. Launch app + Export APK + Share + Copy to Download + No APK yet. Run the app once to build it. + Saved to Download as %1$s + Could not copy the APK to Download + The latest APK is Quick Build\'s live-reload app. Run the app once to build a regular APK, then export it. + A build is running. Export the APK when it finishes. Experimental Experiments on You are using %1$s variant of Code On The Go on a %2$s device. This configuration may work, but it\'ll result in reduced performance and possible security vulnerabilities. Please avoid using this configuration whenever possible.