From cdf5d781d41e287a8706293432d417c61f5cc104 Mon Sep 17 00:00:00 2001 From: Akash Yadav Date: Tue, 17 Nov 2026 00:06:10 +0530 Subject: [PATCH] feat(projects): key the project model by artifact scope --- .../indexing/jvm/ModuleFixtures.kt | 4 +- .../kotlin/fixtures/GradleProjectFixtures.kt | 10 +- .../projects/models/ArtifactScope.kt | 119 +++++++ .../src/main/proto/android.proto | 29 +- .../androidide/projects/ProjectManagerImpl.kt | 49 ++- .../androidide/projects/api/AndroidModule.kt | 108 ++++-- .../androidide/projects/api/JavaModule.kt | 41 ++- .../androidide/projects/api/ModuleProject.kt | 172 ++++++++-- .../AndroidModuleResourceDirectoriesTest.kt | 12 +- .../projects/api/ArtifactScopeSourcesTest.kt | 313 ++++++++++++++++++ .../projects/api/ArtifactScopeTest.kt | 30 ++ .../api/CompileModuleProjectsCycleTest.kt | 10 +- .../api/ModuleOutputClasspathDeltaTest.kt | 4 +- .../tooling/impl/serial/AndroidProjectExts.kt | 33 +- .../tooling/impl/serial/ScopedComponents.kt | 127 +++++++ .../ScopedArtifactsSerializationTest.kt | 185 +++++++++++ .../impl/serial/VariantSourceProvidersTest.kt | 133 +++++--- .../tooling/api/sync/ProjectSyncHelper.kt | 2 +- 18 files changed, 1223 insertions(+), 158 deletions(-) create mode 100644 subprojects/project-models/src/main/java/com/itsaky/androidide/projects/models/ArtifactScope.kt create mode 100644 subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt create mode 100644 subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeTest.kt create mode 100644 subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/ScopedComponents.kt create mode 100644 subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/ScopedArtifactsSerializationTest.kt diff --git a/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/ModuleFixtures.kt b/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/ModuleFixtures.kt index ca666e48ad..7c15f4f694 100644 --- a/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/ModuleFixtures.kt +++ b/lsp/jvm-symbol-index/src/test/kotlin/org/appdevforall/codeonthego/indexing/jvm/ModuleFixtures.kt @@ -9,6 +9,7 @@ import com.itsaky.androidide.projects.api.GradleProject import com.itsaky.androidide.projects.api.JavaModule import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.projects.api.Workspace +import com.itsaky.androidide.projects.models.ArtifactScope import io.mockk.every import io.mockk.spyk import org.junit.rules.TemporaryFolder @@ -90,7 +91,8 @@ internal class ModuleFixtures( ) } - variantDeps.setMainArtifact( + variantDeps.putArtifacts( + ArtifactScope.Main.key, AndroidModels.ArtifactDependencies .newBuilder() .setCompileGraph(graph.build()) diff --git a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt index c63e7f94a5..35475e8ee6 100644 --- a/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt +++ b/lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/fixtures/GradleProjectFixtures.kt @@ -5,6 +5,7 @@ import com.itsaky.androidide.project.Common import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.project.JavaModels import com.itsaky.androidide.projects.api.JavaModule +import com.itsaky.androidide.projects.models.ArtifactScope import java.nio.file.Path import kotlin.io.path.pathString @@ -86,6 +87,11 @@ private fun projectDependencies(projectPaths: List): AndroidModels.Varia ) } return variantDeps - .setMainArtifact(AndroidModels.ArtifactDependencies.newBuilder().setCompileGraph(graph)) - .build() + .putArtifacts( + ArtifactScope.Main.key, + AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build(), + ).build() } diff --git a/subprojects/project-models/src/main/java/com/itsaky/androidide/projects/models/ArtifactScope.kt b/subprojects/project-models/src/main/java/com/itsaky/androidide/projects/models/ArtifactScope.kt new file mode 100644 index 0000000000..e784591e6c --- /dev/null +++ b/subprojects/project-models/src/main/java/com/itsaky/androidide/projects/models/ArtifactScope.kt @@ -0,0 +1,119 @@ +package com.itsaky.androidide.projects.models + +/** + * A component of a module's build that compiles its own sources against its own dependencies: main + * code, test fixtures, or one kind of host (JVM) or device test. + * + * Each scope has exactly one value, so it can key maps and caches. [key] is how the scope is stored + * in the project model, by the tooling server that writes it and the IDE that reads it; [fromKey] + * reads it back. Host and device test keys carry a prefix so one AGP test type name can never name + * two scopes. + */ +sealed class ArtifactScope { + /** The key this scope is stored under in the project model. */ + abstract val key: String + + /** The suffix of this scope's Kotlin analysis module path; empty for [Main]. */ + abstract val moduleSuffix: String + + /** + * Whether this scope's sources may reference [other]'s. Main sees only itself, test fixtures see + * main, and a test sees main and test fixtures; test scopes never see each other. + */ + fun sees(other: ArtifactScope): Boolean = + when (this) { + Main -> other == Main + TestFixtures -> other == Main || other == TestFixtures + is HostTest, is DeviceTest -> other == Main || other == TestFixtures || other == this + } + + /** Main sources: `src/main` and the selected variant's layers over it. */ + data object Main : ArtifactScope() { + override val key = "main" + override val moduleSuffix = "" + } + + /** Test fixtures: `src/testFixtures`, visible to the module's tests. */ + data object TestFixtures : ArtifactScope() { + override val key = "testFixtures" + override val moduleSuffix = "testFixtures" + } + + /** Tests that run on the host JVM, named by the key AGP's model gives them (e.g. `_unit_test_`). */ + data class HostTest( + val type: String, + ) : ArtifactScope() { + override val key = "$HOST_PREFIX$type" + override val moduleSuffix = camelCase(type) + } + + /** Tests that run on a device, named by the key AGP's model gives them (e.g. `_android_test_`). */ + data class DeviceTest( + val type: String, + ) : ArtifactScope() { + override val key = "$DEVICE_PREFIX$type" + override val moduleSuffix = camelCase(type) + } + + companion object { + private const val HOST_PREFIX = "host:" + private const val DEVICE_PREFIX = "device:" + + // The type names are AGP's ComponentTypeImpl artifact names, the keys of its model's test maps. + + /** Unit tests, `src/test`. */ + @JvmField + val UNIT_TEST = HostTest("_unit_test_") + + /** Screenshot tests, `src/screenshotTest`. */ + @JvmField + val SCREENSHOT_TEST = HostTest("_screenshot_test_") + + /** Instrumented tests, `src/androidTest`. */ + @JvmField + val ANDROID_TEST = DeviceTest("_android_test_") + + /** + * Main, test fixtures, unit tests, android tests, then other host and device tests by key: the + * order a file shared by several scopes is attributed in. + */ + @JvmField + val ORDER: Comparator = + compareBy { scope -> + when (scope) { + Main -> 0 + TestFixtures -> 1 + UNIT_TEST -> 2 + ANDROID_TEST -> 3 + is HostTest -> 4 + is DeviceTest -> 5 + } + }.thenBy { it.key } + + /** `_unit_test_` -> `unitTest`, so Kotlin module paths stay readable. */ + private fun camelCase(type: String): String = + type + .split('_') + .filter { it.isNotEmpty() } + .mapIndexed { index, part -> + if (index == + 0 + ) { + part.replaceFirstChar(Char::lowercaseChar) + } else { + part.replaceFirstChar(Char::uppercaseChar) + } + }.joinToString("") + + /** The scope stored under [key], or null when [key] names no scope. */ + @JvmStatic + fun fromKey(key: String): ArtifactScope? = + when { + key == Main.key -> Main + key == TestFixtures.key -> TestFixtures + key.startsWith(HOST_PREFIX) -> HostTest(key.removePrefix(HOST_PREFIX)) + key.startsWith(DEVICE_PREFIX) -> DeviceTest(key.removePrefix(DEVICE_PREFIX)) + else -> null + } + } +} diff --git a/subprojects/project-models/src/main/proto/android.proto b/subprojects/project-models/src/main/proto/android.proto index 2e70d187c9..f4d4fe9858 100644 --- a/subprojects/project-models/src/main/proto/android.proto +++ b/subprojects/project-models/src/main/proto/android.proto @@ -184,14 +184,15 @@ message VariantDependencies { // The name of the variant. It is made up of the build type and flavors (if applicable) string name = 1; - // The dependencies for the variant's main artifact. - ArtifactDependencies mainArtifact = 2; - // The list of external libraries used by all the variants in the module. // // The key for the map entries is the keys found via [com.android.builder.model.v2.ide.GraphItem.key] // and [Library.key] map libraries = 3; + + // The dependencies of each of the variant's components (main, test fixtures, each host and + // device test type), keyed by ArtifactScope.key. A component the variant lacks has no entry. + map artifacts = 2; } // A custom source directory. @@ -220,8 +221,9 @@ message SourceProvider { // Android source set container. message SourceSetContainer { - // The default source provider. - SourceProvider sourceProvider = 1; + // The source provider of each component (src/main, src/test, src/androidTest, ...), keyed by + // ArtifactScope.key. A component the module lacks has no entry. + map sourceProviders = 1; } // View binding options for Android projects. @@ -275,6 +277,17 @@ message AndroidArtifact { int32 targetSdkVersionOverride = 13; } +// The sources one component of a variant adds over that component's default source set. +message VariantArtifactSources { + + // The source providers AGP layers over the component's default source set for this variant: its + // build type, each product flavor, the multi-flavor provider and the variant's own provider. + repeated SourceProvider variantSourceProviders = 1; + + // The component's generated source folders (kapt, KSP, BuildConfig and the like). + repeated string generatedSourceFolderPaths = 2; +} + // An Android project variant. message AndroidVariant { @@ -284,9 +297,8 @@ message AndroidVariant { // The 'main' artifact of the variant. AndroidArtifact mainArtifact = 2; - // The source providers AGP layers over the main source set for this variant: its build - // type, each product flavor, the multi-flavor provider and the variant's own provider. - repeated SourceProvider variantSourceProviders = 3; + // The sources each of the variant's components adds, keyed by ArtifactScope.key. + map artifactSources = 3; } // The Android project model. @@ -324,5 +336,4 @@ message AndroidProject { // The compiler settings for Kotlin sources. optional KotlinCompilerSettings kotlinCompilerSettings = 11; - } \ No newline at end of file diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt index 094c3c695f..1a28d73468 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/ProjectManagerImpl.kt @@ -39,6 +39,7 @@ import com.itsaky.androidide.projects.api.JavaModule import com.itsaky.androidide.projects.api.ModuleProject import com.itsaky.androidide.projects.api.Workspace import com.itsaky.androidide.projects.builder.BuildService +import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.projects.models.resDirs import com.itsaky.androidide.tasks.executeAsync import com.itsaky.androidide.tooling.api.IAndroidProject @@ -430,7 +431,7 @@ class ProjectManagerImpl : } val isResource = - module.mainSourceSet?.sourceProvider?.resDirs?.any { + module.defaultSources(ArtifactScope.Main)?.resDirs?.any { this.pathString.contains(it.path) } ?: false @@ -446,11 +447,11 @@ class ProjectManagerImpl : generateSourcesIfNecessary(event) if (DocumentUtils.isJavaFile(event.file.toPath())) { - IProjectManager.getInstance().findModuleForFile(event.file, false)?.let { - val sourceRoot = it.findSourceRoot(event.file) ?: return@let - - // add the source node entry - it.compileJavaSourceClasses.append(event.file.toPath(), sourceRoot) + IProjectManager.getInstance().findModuleForFile(event.file, false)?.let { module -> + // add the source node entry to main's trie and/or the test scopes' that see this file + module.javaSourceClassesFor(event.file).forEach { (trie, sourceRoot) -> + trie.append(event.file.toPath(), sourceRoot) + } } } } @@ -464,17 +465,19 @@ class ProjectManagerImpl : // Do not check for Java file DocumentUtils.isJavaFile(...) as it checks for file existence as // well. As the file is already deleted, it will always return false if (event.file.extension == "java") { - IProjectManager - .getInstance() - .findModuleForFile( - event.file, - false, - )?.compileJavaSourceClasses - ?.findSource(event.file.toPath()) - ?.let { it.parent?.removeChild(it) } + removeJavaSource(event.file) } } + /** Removes [file] from every Java source trie of its module. */ + private fun removeJavaSource(file: File) { + IProjectManager + .getInstance() + .findModuleForFile(file, false) + ?.allJavaSourceClasses() + ?.forEach { trie -> trie.findSource(file.toPath())?.let { it.parent?.removeChild(it) } } + } + @Suppress("unused") @Subscribe(threadMode = ThreadMode.BACKGROUND) fun onFileRenamed(event: FileRenameEvent) { @@ -483,22 +486,14 @@ class ProjectManagerImpl : // Do not check for Java file DocumentUtils.isJavaFile(...) as it checks for file existence as // well. As the file is already renamed to another filename, it will always return false if (event.file.extension == "java") { - // remove the source node entry - IProjectManager - .getInstance() - .findModuleForFile( - event.file, - false, - )?.compileJavaSourceClasses - ?.findSource(event.file.toPath()) - ?.let { it.parent?.removeChild(it) } + removeJavaSource(event.file) } if (DocumentUtils.isJavaFile(event.newFile.toPath())) { - IProjectManager.getInstance().findModuleForFile(event.newFile, false)?.let { - val sourceRoot = it.findSourceRoot(event.newFile) ?: return@let - // add the new source node entry - it.compileJavaSourceClasses.append(event.newFile.toPath(), sourceRoot) + IProjectManager.getInstance().findModuleForFile(event.newFile, false)?.let { module -> + module.javaSourceClassesFor(event.newFile).forEach { (trie, sourceRoot) -> + trie.append(event.newFile.toPath(), sourceRoot) + } } } } diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt index a2c48ed5e3..494d82ced7 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/AndroidModule.kt @@ -25,13 +25,13 @@ import com.itsaky.androidide.builder.model.UNKNOWN_PACKAGE import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.projects.models.artifact import com.itsaky.androidide.projects.models.bootClassPaths import com.itsaky.androidide.projects.models.buildDir import com.itsaky.androidide.projects.models.classJars import com.itsaky.androidide.projects.models.classesJar import com.itsaky.androidide.projects.models.compileJarFiles -import com.itsaky.androidide.projects.models.generatedSourceFolders import com.itsaky.androidide.projects.models.javaDirs import com.itsaky.androidide.projects.models.kotlinDirs import com.itsaky.androidide.projects.models.resDirs @@ -85,6 +85,16 @@ open class AndroidModule( fun getVariant(name: String): AndroidModels.AndroidVariant? = variantList.firstOrNull { it.name == name } + /** The default source provider of [scope] (`src/main`, `src/test`, ...), if the module has one. */ + internal fun defaultSources(scope: ArtifactScope): AndroidModels.SourceProvider? = mainSourceSet?.sourceProvidersMap?.get(scope.key) + + /** What the selected variant's [scope] component adds over its default source set. */ + private fun variantSources(scope: ArtifactScope): AndroidModels.VariantArtifactSources? = + getSelectedVariant()?.artifactSourcesMap?.get(scope.key) + + /** The dependencies of the selected variant's [scope] component, if the variant has it. */ + private fun dependenciesOf(scope: ArtifactScope): AndroidModels.ArtifactDependencies? = variantDependencies.artifactsMap[scope.key] + fun getResourceDirectories(): Set { if (mainSourceSet == null) { log.error("No main source set found in application module: {}", name) @@ -92,11 +102,11 @@ open class AndroidModule( } val dirs = mutableSetOf() - dirs.addAll(mainSourceSet?.sourceProvider?.resDirs ?: emptyList()) + dirs.addAll(defaultSources(ArtifactScope.Main)?.resDirs ?: emptyList()) // src//res, src//res and the variant's own res dir are resources of the // selected variant as much as src/main/res is; a save there must regenerate R too. - getSelectedVariant()?.variantSourceProvidersList?.forEach { provider -> + variantSources(ArtifactScope.Main)?.variantSourceProvidersList?.forEach { provider -> dirs.addAll(provider.resDirs) } @@ -109,28 +119,29 @@ open class AndroidModule( return dirs } - override fun getSourceDirectories(): Set { + // The components the selected variant has: one AGP does not report for it is no scope, even if + // the module has its source set (src/androidTest while a non-tested build type is selected). + override fun getArtifactScopes(): List = + (listOf(ArtifactScope.Main) + variantDependencies.artifactsMap.keys.mapNotNull(ArtifactScope::fromKey)) + .distinct() + .sortedWith(ArtifactScope.ORDER) + + override fun getSourceDirectories(scope: ArtifactScope): Set { if (mainSourceSet == null) { log.warn( "No main source set is available for project {}. Cannot get source directories.", name, ) - return mutableSetOf() + return emptySet() } - - // src/main/java - val sources = mainSourceSet.sourceProvider.javaDirs.toMutableSet() - - // src/main/kotlin - sources.addAll(mainSourceSet.sourceProvider.kotlinDirs) - - // build/generated/** - // AIDL, ViewHolder, Renderscript, BuildConfig i.e every generated source sources - val selectedVariant = getSelectedVariant() - if (selectedVariant != null) { - sources.addAll(selectedVariant.mainArtifact.generatedSourceFolders) + if (scope != ArtifactScope.Main && dependenciesOf(scope) == null) { + return emptySet() } - return sources + val provider = defaultSources(scope) ?: return emptySet() + + // build/generated/**: AIDL, BuildConfig, kapt, KSP and every other generated source + val generated = variantSources(scope)?.generatedSourceFolderPathsList.orEmpty().map(::File) + return (provider.javaDirs + provider.kotlinDirs + generated).toSet() } override fun getCompileSourceDirectories(): Set { @@ -140,6 +151,59 @@ open class AndroidModule( return dirs } + override fun getCompileModuleProjects(scope: ArtifactScope): List { + if (scope == ArtifactScope.Main) { + return getCompileModuleProjects() + } + // Seeded with this module so a test fixture that depends back on it (`:testutils` -> + // `:app`) is not re-expanded. Not on the recursion path: that back-edge is legal, not a cycle. + val visited = hashSetOf(path) + val recursionPath = ArrayDeque() + val result = mutableListOf() + for (module in directProjectDependencies(scope)) { + result.add(module) + result.addAll(module.getCompileModuleProjects(visited, recursionPath)) + } + return result.filter { it.path != path }.distinctBy { it.path } + } + + /** The modules of the project libraries at the root of [scope]'s compile graph, excluding this one. */ + private fun directProjectDependencies(scope: ArtifactScope): List { + val graph = dependenciesOf(scope)?.compileGraph ?: return emptyList() + val root = IProjectManager.getInstance().workspace ?: return emptyList() + return graph.rootList + .mapNotNull { nodeId -> graph.nodeList.getOrNull(nodeId)?.let { graph.keyList.getOrNull(it.keyId) } } + .mapNotNull { key -> variantDependencies.librariesMap[key] } + .filter { it.type == AndroidModels.LibraryType.Project } + .mapNotNull { library -> root.findByPath(library.projectInfo.projectPath) as? ModuleProject } + .filter { it.path != path } + } + + override fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean, + ): Set { + if (scope == ArtifactScope.Main) { + return getCompileClasspaths(excludeSourceGeneratedClassPath) + } + val artifact = dependenciesOf(scope) ?: return emptySet() + val project = IProjectManager.getInstance().workspace ?: return emptySet() + + val result = getCompileClasspaths(excludeSourceGeneratedClassPath).toMutableSet() + val graph = artifact.compileGraph + collectLibraries( + root = project, + graph = graph, + nodeIds = graph.rootList, + result = result, + excludeSourceGeneratedClassPath = excludeSourceGeneratedClassPath, + visited = HashSet(), + // A test graph that reaches back to this module must not re-expand it. + moduleVisited = hashSetOf(path), + ) + return result + } + override fun getModuleClasspaths(): Set = mutableSetOf().apply { add(getGeneratedJar()) @@ -172,7 +236,7 @@ open class AndroidModule( } else { result.addAll(getModuleClasspaths()) } - val graph = variantDependencies.mainArtifact.compileGraph + val graph = dependenciesOf(ArtifactScope.Main)?.compileGraph ?: AndroidModels.DependencyGraph.getDefaultInstance() collectLibraries( root = project, graph = graph, @@ -395,7 +459,7 @@ open class AndroidModule( try { val result = mutableListOf() - val graph = variantDependencies.mainArtifact.compileGraph + val graph = dependenciesOf(ArtifactScope.Main)?.compileGraph ?: AndroidModels.DependencyGraph.getDefaultInstance() val libraryMap = variantDependencies.librariesMap for (nodeId in graph.rootList) { val node = graph.nodeList.getOrNull(nodeId) @@ -499,7 +563,7 @@ open class AndroidModule( fun getResourceTable(): ResourceTable? { val namespace = this.namespace ?: return null - val resDirs = mainSourceSet?.sourceProvider?.resDirs ?: return null + val resDirs = defaultSources(ArtifactScope.Main)?.resDirs ?: return null return ResourceTableRegistry.getInstance().forPackage(namespace, *resDirs.toTypedArray()) } @@ -511,7 +575,7 @@ open class AndroidModule( CompletableFuture.runAsync { val tableRegistry = ResourceTableRegistry.getInstance() - val resDirs = mainSourceSet?.sourceProvider?.resDirs ?: return@runAsync + val resDirs = defaultSources(ArtifactScope.Main)?.resDirs ?: return@runAsync tableRegistry.removeTable(this.namespace) tableRegistry.forPackage(this.namespace, *resDirs.toTypedArray()) } diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/JavaModule.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/JavaModule.kt index 9732a9a3c2..a5c0a24b18 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/JavaModule.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/JavaModule.kt @@ -21,6 +21,7 @@ import com.google.protobuf.MessageLite import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.project.JavaModels import com.itsaky.androidide.projects.IProjectManager +import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.projects.models.buildDir import com.itsaky.androidide.projects.models.directory import com.itsaky.androidide.projects.models.jarFile @@ -38,6 +39,7 @@ class JavaModule( companion object { const val SCOPE_COMPILE = "COMPILE" const val SCOPE_RUNTIME = "RUNTIME" + const val SCOPE_TEST = "TEST" } init { @@ -72,7 +74,16 @@ class JavaModule( override fun getClassPaths(): Set = getModuleClasspaths() - override fun getSourceDirectories(): Set { + override fun getArtifactScopes(): List = listOf(ArtifactScope.Main, ArtifactScope.UNIT_TEST) + + override fun getSourceDirectories(scope: ArtifactScope): Set = + when (scope) { + ArtifactScope.Main -> mainSourceDirectories() + ArtifactScope.UNIT_TEST -> contentRootList.flatMap { root -> root.testDirectoryList.map { it.directory } }.toSet() + else -> emptySet() + } + + private fun mainSourceDirectories(): Set { val sources = mutableSetOf() contentRootList.forEach { contentRoot -> sources.addAll( @@ -90,6 +101,34 @@ class JavaModule( return dirs } + // getDependencyClassPaths does not filter by scope, so test dependencies are already on the + // compile classpath. + override fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean, + ): Set = + when (scope) { + ArtifactScope.Main, ArtifactScope.UNIT_TEST -> getCompileClasspaths(excludeSourceGeneratedClassPath) + else -> emptySet() + } + + // Unit tests see main's module dependencies plus the TEST-scoped ones (testImplementation). + override fun getCompileModuleProjects(scope: ArtifactScope): List { + if (scope == ArtifactScope.Main) { + return getCompileModuleProjects() + } + if (scope != ArtifactScope.UNIT_TEST) { + return emptyList() + } + val root = IProjectManager.getInstance().workspace ?: return emptyList() + val testOnly = + dependencyList + .filter { it.hasModule() && it.scope == SCOPE_TEST } + .mapNotNull { root.findByPath(it.module.projectPath) as? ModuleProject } + .filter { it.path != path } + return (getCompileModuleProjects() + testOnly).distinctBy { it.path } + } + override fun getModuleClasspaths(): Set = mutableSetOf(getClassesJar()) override fun getCompileClasspaths( diff --git a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt index 27f5260a93..5e610a6f83 100644 --- a/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt +++ b/subprojects/projects/src/main/java/com/itsaky/androidide/projects/api/ModuleProject.kt @@ -23,6 +23,7 @@ import com.itsaky.androidide.javac.services.fs.CacheFSInfoSingleton import com.itsaky.androidide.lookup.Lookup import com.itsaky.androidide.project.Common import com.itsaky.androidide.project.GradleModels +import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.projects.models.DEFAULT_COMPILER_SETTINGS import com.itsaky.androidide.projects.models.bootClassPaths import com.itsaky.androidide.projects.util.BootClasspathProvider @@ -33,6 +34,7 @@ import com.itsaky.androidide.utils.StopWatch import org.slf4j.LoggerFactory import java.io.File import java.nio.file.Path +import java.util.concurrent.ConcurrentHashMap import kotlin.io.path.pathString /** @@ -69,15 +71,79 @@ abstract class ModuleProject( val COMPLETION_MODULE_KEY = Lookup.Key() } + /** The Java classes main code compiles against: this module's and its compile dependencies' sources. */ @JvmField val compileJavaSourceClasses = SourceClassTrie() + // Each scope's trie holds the main sources too, so a test compilation reads one trie, as main does. + private val testJavaSourceClasses = ConcurrentHashMap() + + /** The Java classes [scope] compiles against. */ + fun javaSourceClasses(scope: ArtifactScope): SourceClassTrie = + if (scope == ArtifactScope.Main) { + compileJavaSourceClasses + } else { + testJavaSourceClasses.computeIfAbsent(scope) { SourceClassTrie() } + } + + /** The scopes of this module other than [ArtifactScope.Main]. */ + private fun nonMainScopes(): List = getArtifactScopes().filter { it != ArtifactScope.Main } + + /** The scope whose own source directories hold [file], in [getArtifactScopes] order; main's for any other file. */ + fun artifactScopeOf(file: Path): ArtifactScope = + getArtifactScopes().firstOrNull { scope -> getSourceDirectories(scope).any { file.startsWith(it.toPath()) } } + ?: ArtifactScope.Main + + fun artifactScopeOf(file: File): ArtifactScope = artifactScopeOf(file.toPath()) + + /** + * The tries a Java [file] belongs in, each with the source root to index it under: a main source + * goes in main's trie and every other scope's, any other source in the trie of each scope that + * sees a scope holding its dir (a test fixture goes in the fixtures' and every test scope's). + * Empty when the file is in no source directory. + */ + fun javaSourceClassesFor(file: File): List> { + findSourceRoot(file)?.let { root -> + return listOf(compileJavaSourceClasses to root) + + nonMainScopes() + .filter { getSourceDirectories(it).isNotEmpty() } + .map { javaSourceClasses(it) to root } + } + val path = file.toPath() + // Every matching scope, not the first: a dir such as src/sharedTest can be in both. + val scopes = nonMainScopes() + return scopes.mapNotNull { scope -> + scopes + .filter(scope::sees) + .flatMap(::getSourceDirectories) + .firstOrNull { path.startsWith(it.toPath()) } + ?.let { javaSourceClasses(scope) to it.toPath() } + } + } + + /** Every Java source trie of this module, for removing a file that may be in any of them. */ + fun allJavaSourceClasses(): List = listOf(compileJavaSourceClasses) + testJavaSourceClasses.values + + /** + * The scopes of this module's selected variant: [ArtifactScope.Main] first, then the others + * the module has. + */ + abstract fun getArtifactScopes(): List + /** - * Get the source directories of this module (non-transitive i.e for this module only). + * Get the main source directories of this module (non-transitive i.e for this module only). * * @return The source directories. */ - abstract fun getSourceDirectories(): Set + fun getSourceDirectories(): Set = getSourceDirectories(ArtifactScope.Main) + + /** + * Get the source directories of this module's [scope] (non-transitive). Non-main scopes are + * kept out of main's, so neither main code nor dependent modules see test code. + * + * @return The source directories, or an empty set if the module has no such scope. + */ + abstract fun getSourceDirectories(scope: ArtifactScope): Set /** * Get the source directories with compile scope. This must include source directories of @@ -87,6 +153,39 @@ abstract class ModuleProject( */ abstract fun getCompileSourceDirectories(): Set + /** + * Get the classpaths that [scope] sources compile against. For a non-main scope: everything in + * [getCompileClasspaths] plus that scope's own dependencies. + * + * @param excludeSourceGeneratedClassPath See [getCompileClasspaths]. + * @return The compile classpaths, or an empty set if the module has no such scope. + */ + abstract fun getCompileClasspaths( + scope: ArtifactScope, + excludeSourceGeneratedClassPath: Boolean = false, + ): Set + + /** + * Get the module projects [scope] compiles against, transitively. For a non-main scope: main's, + * plus those only that scope depends on, such as `testImplementation(project(":lib"))`. Never + * this module. + */ + abstract fun getCompileModuleProjects(scope: ArtifactScope): List + + /** + * The source directories [scope] compiles against. For main, [getCompileSourceDirectories]; for + * any other scope: main's, this module's sources of every scope [scope] sees (itself and test + * fixtures), and the sources of the modules only that scope depends on. + */ + fun getCompileSourceDirectories(scope: ArtifactScope): Set = + if (scope == ArtifactScope.Main) { + getCompileSourceDirectories() + } else { + getCompileSourceDirectories() + + nonMainScopes().filter(scope::sees).flatMap(::getSourceDirectories) + + getCompileModuleProjects(scope).flatMap { it.getSourceDirectories() } + } + /** * Get the classpaths for this module project. The returned list always included the * `classes.jar`. @@ -210,7 +309,11 @@ abstract class ModuleProject( * @param file The file to find the source root for. * @return The source root (directory) of the given file, or `null` if not found. */ - fun findSourceRoot(file: File): Path? = getCompileSourceDirectories().find { file.path.startsWith(it.path) }?.toPath() + fun findSourceRoot(file: File): Path? { + // Path.startsWith matches whole directories: src/main/javaTest is not under src/main/java. + val path = file.toPath() + return getCompileSourceDirectories().map(File::toPath).find { path.startsWith(it) } + } /** Indexes the source files' classes and prepares the classpaths for the compiler. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) @@ -237,34 +340,51 @@ abstract class ModuleProject( @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) fun indexSources() { - this.compileJavaSourceClasses.clear() + allJavaSourceClasses().forEach { it.clear() } val watch = StopWatch("Indexing sources") - var count = 0 - getCompileSourceDirectories().forEach { - val sourceDir = it.toPath() - it - .walk() - .filter { file -> file.isFile && file.exists() && DocumentUtils.isJavaFile(file.toPath()) } - .map { file -> file.toPath() } - .forEach { file -> - this.compileJavaSourceClasses.append(file, sourceDir) - count++ - } + val mainSources = javaSourcesIn(getCompileSourceDirectories()) + mainSources.forEach { (file, root) -> compileJavaSourceClasses.append(file, root) } + + var count = mainSources.size + for (scope in nonMainScopes()) { + if (getSourceDirectories(scope).isEmpty()) { + continue + } + val trie = javaSourceClasses(scope) + val testSources = javaSourcesIn(getCompileSourceDirectories(scope) - getCompileSourceDirectories()) + (mainSources + testSources).forEach { (file, root) -> trie.append(file, root) } + count += testSources.size } watch.log() log.debug("Found {} source files.", count) } + /** Every Java file under [dirs], paired with the directory it was found under. */ + private fun javaSourcesIn(dirs: Collection): List> = + dirs.flatMap { dir -> + val root = dir.toPath() + dir + .walk() + .filter { file -> file.isFile && file.exists() && DocumentUtils.isJavaFile(file.toPath()) } + .map { file -> file.toPath() to root } + .toList() + } + fun getSourceFilesInDir(dir: Path): List = this.compileJavaSourceClasses.getSourceFilesInDir(dir) - fun packageNameOrEmpty(file: Path?): String { + /** The package of [file] as [scope]'s compilation sees it. */ + @JvmOverloads + fun packageNameOrEmpty( + file: Path?, + scope: ArtifactScope = ArtifactScope.Main, + ): String { if (file == null) { return "" } - val sourceNode = searchSourceFileRelatively(file) + val sourceNode = searchSourceFileRelatively(file, scope) if (sourceNode != null) { return sourceNode.packageName } @@ -272,8 +392,12 @@ abstract class ModuleProject( return "" } - private fun searchSourceFileRelatively(file: Path?): SourceNode? { - for (source in getCompileSourceDirectories().map(File::toPath)) { + private fun searchSourceFileRelatively( + file: Path?, + scope: ArtifactScope, + ): SourceNode? { + val roots = getCompileSourceDirectories(scope) + for (source in roots.map(File::toPath)) { val relative = source.relativize(file) if (relative.pathString.contains("..")) { // This is most probably not the one we're expecting @@ -283,7 +407,7 @@ abstract class ModuleProject( var name = relative.pathString.substringBeforeLast(".java") name = name.replace('/', '.') - val node = this.compileJavaSourceClasses.findNode(name) + val node = javaSourceClasses(scope).findNode(name) if (node != null && node is SourceNode) { return node } @@ -315,8 +439,12 @@ abstract class ModuleProject( return "" } - fun listClassesFromSourceDirs(packageName: String): List = - compileJavaSourceClasses + @JvmOverloads + fun listClassesFromSourceDirs( + packageName: String, + scope: ArtifactScope = ArtifactScope.Main, + ): List = + javaSourceClasses(scope) .findInPackage(packageName) .filterIsInstance() diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/AndroidModuleResourceDirectoriesTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/AndroidModuleResourceDirectoriesTest.kt index 8567c4633e..7282dfba4e 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/AndroidModuleResourceDirectoriesTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/AndroidModuleResourceDirectoriesTest.kt @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.models.ArtifactScope import com.itsaky.androidide.tooling.api.models.BuildVariantInfo import org.junit.After import org.junit.Rule @@ -90,8 +91,13 @@ class AndroidModuleResourceDirectoriesTest { .newBuilder() .setName(name) .setMainArtifact(AndroidModels.AndroidArtifact.newBuilder().setName("main")) - .addVariantSourceProviders(sourceProvider(res)) - .build() + .putArtifactSources( + ArtifactScope.Main.key, + AndroidModels.VariantArtifactSources + .newBuilder() + .addVariantSourceProviders(sourceProvider(res)) + .build(), + ).build() /** Install one application module with `debug` and `release` variants and select [selectedVariant]. */ private fun installApp(selectedVariant: String): AndroidModule { @@ -100,7 +106,7 @@ class AndroidModuleResourceDirectoriesTest { .newBuilder() .setProjectType(AndroidModels.ProjectType.ApplicationProject) .setMainSourceSet( - AndroidModels.SourceSetContainer.newBuilder().setSourceProvider(sourceProvider(mainRes)), + AndroidModels.SourceSetContainer.newBuilder().putSourceProviders(ArtifactScope.Main.key, sourceProvider(mainRes)), ).addVariant(variant("debug", debugRes)) .addVariant(variant("release", releaseRes)) .build() diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt new file mode 100644 index 0000000000..a6fff0cddc --- /dev/null +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeSourcesTest.kt @@ -0,0 +1,313 @@ +package com.itsaky.androidide.projects.api + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.project.AndroidModels +import com.itsaky.androidide.project.GradleModels +import com.itsaky.androidide.project.JavaModels +import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.models.ArtifactScope +import com.itsaky.androidide.tooling.api.models.BuildVariantInfo +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +/** + * Unit tests and android tests are separate scopes (ADFA-7115): each sees main plus its own sources + * and dependencies, never the other's, and main never sees either. + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE) +class ArtifactScopeSourcesTest { + private val mainJava = File("/p/app/src/main/java") + private val unitJava = File("/p/app/src/test/java") + private val unitKotlin = File("/p/app/src/test/kotlin") + private val deviceJava = File("/p/app/src/androidTest/java") + private val unitGenerated = File("/p/app/build/generated/ksp/debugUnitTest/java") + private val screenshotJava = File("/p/app/src/screenshotTest/java") + private val fixturesJava = File("/p/app/src/testFixtures/java") + + @After + fun tearDown() { + runCatching { ProjectManagerImpl.getInstance().workspace = null } + ProjectManagerImpl.getInstance().androidBuildVariants = emptyMap() + } + + @Test + fun `each test scope has only its own source directories`() { + val app = app(withTests = true) + install(app) + + assertThat(app.getSourceDirectories(ArtifactScope.UNIT_TEST)).containsExactly(unitJava, unitKotlin) + assertThat(app.getSourceDirectories(ArtifactScope.ANDROID_TEST)).containsExactly(deviceJava) + } + + @Test + fun `main source directories leave out test sources`() { + val app = app(withTests = true) + install(app) + + assertThat(app.getSourceDirectories()).containsExactly(mainJava) + assertThat(app.getCompileSourceDirectories()).containsExactly(mainJava) + } + + @Test + fun `each test scope compiles against main plus its own dependencies`() { + val app = app(withTests = true) + install(app) + + assertThat(app.getCompileClasspaths(ArtifactScope.UNIT_TEST, true)) + .containsExactly(File("/jars/main.jar"), File("/jars/junit.jar")) + assertThat(app.getCompileClasspaths(ArtifactScope.ANDROID_TEST, true)) + .containsExactly(File("/jars/main.jar"), File("/jars/espresso.jar")) + assertThat(app.getCompileClasspaths(true)).containsExactly(File("/jars/main.jar")) + } + + @Test + fun `a project dependency of a test scope contributes its classpath`() { + val app = app(withTests = true, unitTestProject = ":lib") + val lib = lib() + install(app, lib) + + assertThat(app.getCompileClasspaths(ArtifactScope.UNIT_TEST, true)).contains(File("/jars/lib.jar")) + assertThat(app.getCompileClasspaths(ArtifactScope.ANDROID_TEST, true)).doesNotContain(File("/jars/lib.jar")) + } + + @Test + fun `a test-only project dependency is a module the test scope compiles against`() { + val app = app(withTests = true, unitTestProject = ":lib") + install(app, lib()) + + assertThat(app.getCompileModuleProjects(ArtifactScope.UNIT_TEST).map { it.path }).containsExactly(":lib") + assertThat(app.getCompileModuleProjects(ArtifactScope.ANDROID_TEST)).isEmpty() + assertThat(app.getCompileModuleProjects()).isEmpty() + } + + @Test + fun `a test fixture that depends back on the module does not list the module`() { + val app = app(withTests = true, unitTestProject = ":lib") + install(app, lib(dependsOn = ":app")) + + assertThat(app.getCompileModuleProjects(ArtifactScope.UNIT_TEST).map { it.path }).containsExactly(":lib") + } + + @Test + fun `the selected variant's generated test sources are test source directories`() { + val app = app(withTests = true) + install(app) + ProjectManagerImpl.getInstance().androidBuildVariants = + mapOf(":app" to BuildVariantInfo(":app", listOf("debug"), "debug")) + + assertThat(app.getSourceDirectories(ArtifactScope.UNIT_TEST)).contains(unitGenerated) + assertThat(app.getSourceDirectories(ArtifactScope.ANDROID_TEST)).doesNotContain(unitGenerated) + assertThat(app.getSourceDirectories()).doesNotContain(unitGenerated) + } + + @Test + fun `a module without test source sets has empty test scopes`() { + val app = app(withTests = false) + install(app) + + for (scope in listOf(ArtifactScope.UNIT_TEST, ArtifactScope.ANDROID_TEST)) { + assertThat(app.getSourceDirectories(scope)).isEmpty() + assertThat(app.getCompileClasspaths(scope, true)).isEmpty() + } + } + + @Test + fun `req 2 - screenshot tests are their own scope`() { + val app = app(withTests = true, extraScopes = mapOf(ArtifactScope.SCREENSHOT_TEST to screenshotJava)) + install(app) + + assertThat(app.getArtifactScopes()).contains(ArtifactScope.SCREENSHOT_TEST) + assertThat(app.getSourceDirectories(ArtifactScope.SCREENSHOT_TEST)).containsExactly(screenshotJava) + assertThat(app.getSourceDirectories(ArtifactScope.UNIT_TEST)).doesNotContain(screenshotJava) + } + + @Test + fun `req 3 - a component AGP does not report is not a scope`() { + val app = app(withTests = false) + install(app) + + assertThat(app.getArtifactScopes()).containsExactly(ArtifactScope.Main) + } + + @Test + fun `req 5 - test fixtures sources are visible to unit tests but not to main`() { + val app = app(withTests = true, extraScopes = mapOf(ArtifactScope.TestFixtures to fixturesJava)) + install(app) + + assertThat(app.getCompileSourceDirectories(ArtifactScope.UNIT_TEST)).contains(fixturesJava) + assertThat(app.getCompileSourceDirectories(ArtifactScope.Main)).doesNotContain(fixturesJava) + } + + @Test + fun `a java module's test directories are its unit test scope`() { + val javaTest = File("/p/jvm/src/test/java") + val module = + JavaModule( + gradleProject(":jvm") + .setJavaProject( + JavaModels.JavaProject.newBuilder().addContentRoot( + JavaModels.JavaContentRoot + .newBuilder() + .addSourceDirectory(JavaModels.JavaSourceDirectory.newBuilder().setDirectoryPath("/p/jvm/src/main/java")) + .addTestDirectory(JavaModels.JavaSourceDirectory.newBuilder().setDirectoryPath(javaTest.path)), + ), + ).build(), + ) + install(module) + + assertThat(module.getSourceDirectories(ArtifactScope.UNIT_TEST)).containsExactly(javaTest) + assertThat(module.getSourceDirectories(ArtifactScope.ANDROID_TEST)).isEmpty() + assertThat(module.getSourceDirectories()).doesNotContain(javaTest) + } + + @Test + fun `a new test fixtures file is indexed for every scope that sees fixtures`() { + val app = app(withTests = true, extraScopes = mapOf(ArtifactScope.TestFixtures to fixturesJava)) + install(app) + + val tries = app.javaSourceClassesFor(File(fixturesJava, "a/Fixture.java")).map { it.first } + + assertThat(tries).containsExactly( + app.javaSourceClasses(ArtifactScope.TestFixtures), + app.javaSourceClasses(ArtifactScope.UNIT_TEST), + app.javaSourceClasses(ArtifactScope.ANDROID_TEST), + ) + } + + /** An app module; [extraScopes] adds scopes with one source dir and main's dependencies. */ + private fun app( + withTests: Boolean, + unitTestProject: String? = null, + extraScopes: Map = emptyMap(), + ): AndroidModule { + val sourceSet = AndroidModels.SourceSetContainer.newBuilder().putSourceProviders(ArtifactScope.Main.key, provider(mainJava)) + val deps = + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putArtifacts(ArtifactScope.Main.key, artifact("main")) + .putLibraries("main", jar("main")) + if (withTests) { + sourceSet + .putSourceProviders(ArtifactScope.UNIT_TEST.key, provider(unitJava, unitKotlin)) + .putSourceProviders(ArtifactScope.ANDROID_TEST.key, provider(deviceJava)) + deps + .putArtifacts(ArtifactScope.UNIT_TEST.key, artifact(*listOfNotNull("main", "junit", unitTestProject).toTypedArray())) + .putArtifacts(ArtifactScope.ANDROID_TEST.key, artifact("main", "espresso")) + .putLibraries("junit", jar("junit")) + .putLibraries("espresso", jar("espresso")) + unitTestProject?.let { deps.putLibraries(it, projectLibrary(it)) } + } + extraScopes.forEach { (scope, dir) -> + sourceSet.putSourceProviders(scope.key, provider(dir)) + deps.putArtifacts(scope.key, artifact("main")) + } + return AndroidModule( + gradleProject(":app") + .setAndroidProject( + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.ApplicationProject) + .setMainSourceSet(sourceSet) + .setVariantDependencies(deps) + .addVariant( + AndroidModels.AndroidVariant + .newBuilder() + .setName("debug") + .setMainArtifact(AndroidModels.AndroidArtifact.newBuilder().setName("main")) + .putArtifactSources( + ArtifactScope.UNIT_TEST.key, + AndroidModels.VariantArtifactSources + .newBuilder() + .addGeneratedSourceFolderPaths(unitGenerated.path) + .build(), + ), + ), + ).build(), + ) + } + + private fun lib(dependsOn: String? = null): AndroidModule { + val deps = + AndroidModels.VariantDependencies + .newBuilder() + .setName("debug") + .putArtifacts(ArtifactScope.Main.key, artifact(*listOfNotNull("lib", dependsOn).toTypedArray())) + .putLibraries("lib", jar("lib")) + dependsOn?.let { deps.putLibraries(it, projectLibrary(it)) } + val project = + AndroidModels.AndroidProject + .newBuilder() + .setProjectType(AndroidModels.ProjectType.LibraryProject) + return AndroidModule(gradleProject(":lib").setAndroidProject(project.setVariantDependencies(deps)).build()) + } + + private fun provider(vararg dirs: File): AndroidModels.SourceProvider { + val builder = AndroidModels.SourceProvider.newBuilder() + dirs.forEach { if (it.path.endsWith("kotlin")) builder.addKotlinDirs(it.path) else builder.addJavaDirs(it.path) } + return builder.build() + } + + /** An artifact whose compile graph has one root node per key. */ + private fun artifact(vararg keys: String): AndroidModels.ArtifactDependencies { + val graph = AndroidModels.DependencyGraph.newBuilder() + keys.forEachIndexed { index, key -> + graph + .addKey(key) + .addNode(AndroidModels.GraphNode.newBuilder().setKeyId(index)) + .addRoot(index) + } + return AndroidModels.ArtifactDependencies + .newBuilder() + .setCompileGraph(graph) + .build() + } + + private fun jar(key: String): AndroidModels.Library = + AndroidModels.Library + .newBuilder() + .setKey(key) + .setType(AndroidModels.LibraryType.ExternalJavaLibrary) + .setArtifactPath("/jars/$key.jar") + .build() + + private fun projectLibrary(path: String): AndroidModels.Library = + AndroidModels.Library + .newBuilder() + .setKey(path) + .setType(AndroidModels.LibraryType.Project) + .setProjectInfo( + AndroidModels.ProjectInfo + .newBuilder() + .setProjectPath(path), + ).build() + + private fun gradleProject(path: String): GradleModels.GradleProject.Builder { + val dir = "/p${path.replace(':', '/')}" + return GradleModels.GradleProject + .newBuilder() + .setName(path.trimStart(':')) + .setPath(path) + .setProjectDirPath(dir) + .setBuildDirPath("$dir/build") + .setBuildScriptPath("$dir/build.gradle") + } + + private fun install(vararg modules: ModuleProject) { + val root = + GradleProject( + GradleModels.GradleProject + .newBuilder() + .setName("root") + .setPath(":") + .build(), + ) + ProjectManagerImpl.getInstance().workspace = + Workspace(rootProject = root, subProjects = modules.toList(), syncIssues = emptyList()) + } +} diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeTest.kt new file mode 100644 index 0000000000..cd73deaab8 --- /dev/null +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ArtifactScopeTest.kt @@ -0,0 +1,30 @@ +package com.itsaky.androidide.projects.api + +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.projects.models.ArtifactScope +import org.junit.Test + +class ArtifactScopeTest { + private val all = + listOf( + ArtifactScope.Main, + ArtifactScope.TestFixtures, + ArtifactScope.UNIT_TEST, + ArtifactScope.SCREENSHOT_TEST, + ArtifactScope.ANDROID_TEST, + ) + + @Test + fun `fromKey round-trips every scope's key`() { + for (scope in all) { + assertThat(ArtifactScope.fromKey(scope.key)).isEqualTo(scope) + } + } + + @Test + fun `known scopes use the keys AGP's sync model uses`() { + assertThat(ArtifactScope.UNIT_TEST.key).isEqualTo("host:_unit_test_") + assertThat(ArtifactScope.SCREENSHOT_TEST.key).isEqualTo("host:_screenshot_test_") + assertThat(ArtifactScope.ANDROID_TEST.key).isEqualTo("device:_android_test_") + } +} diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt index d115016047..e1b617906b 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/CompileModuleProjectsCycleTest.kt @@ -21,6 +21,7 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.models.ArtifactScope import org.junit.After import org.junit.Test import org.junit.runner.RunWith @@ -91,7 +92,8 @@ class CompileModuleProjectsCycleTest { ).build(), ) } - variantDeps.setMainArtifact( + variantDeps.putArtifacts( + ArtifactScope.Main.key, AndroidModels.ArtifactDependencies .newBuilder() .setCompileGraph(graph.build()) @@ -155,7 +157,8 @@ class CompileModuleProjectsCycleTest { .setName("debug") .putLibraries("rootLib", externalJavaLibrary("rootLib", rootJar)) .putLibraries("transitiveLib", externalJavaLibrary("transitiveLib", transitiveJar)) - .setMainArtifact( + .putArtifacts( + ArtifactScope.Main.key, AndroidModels.ArtifactDependencies .newBuilder() .setCompileGraph(graph.build()) @@ -211,7 +214,8 @@ class CompileModuleProjectsCycleTest { .newBuilder() .setName("debug") .putLibraries("rootLib", externalJavaLibrary("rootLib", "/tmp/root.jar")) - .setMainArtifact( + .putArtifacts( + ArtifactScope.Main.key, AndroidModels.ArtifactDependencies .newBuilder() .setCompileGraph(graph.build()) diff --git a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ModuleOutputClasspathDeltaTest.kt b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ModuleOutputClasspathDeltaTest.kt index 330761ba94..6b061ddc0c 100644 --- a/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ModuleOutputClasspathDeltaTest.kt +++ b/subprojects/projects/src/test/java/com/itsaky/androidide/projects/api/ModuleOutputClasspathDeltaTest.kt @@ -4,6 +4,7 @@ import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.project.AndroidModels import com.itsaky.androidide.project.GradleModels import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.projects.models.ArtifactScope import io.mockk.every import io.mockk.spyk import org.junit.After @@ -140,7 +141,8 @@ class ModuleOutputClasspathDeltaTest { ) } - variantDeps.setMainArtifact( + variantDeps.putArtifacts( + ArtifactScope.Main.key, AndroidModels.ArtifactDependencies .newBuilder() .setCompileGraph(graph.build()) diff --git a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt index ec7f3a7d93..6621a547ce 100644 --- a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt +++ b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/AndroidProjectExts.kt @@ -82,8 +82,8 @@ fun createAndroidProjectProtoModel( fun VariantDependencies.asProtoModel() = VariantDependencies( name = this.name, - mainArtifact = this.mainArtifact.asProtoModel(), librariesMap = this.libraries.mapValues { entry -> entry.value.asProtoModel() }, + artifactsMap = scopedArtifacts().mapValues { entry -> entry.value.asProtoModel() }, ) fun Library.asProtoModel() = @@ -206,7 +206,10 @@ fun UnresolvedDependency.asProtoModel() = cause = this.cause, ) -fun SourceSetContainer.asProtoModel() = SourceSetContainer(sourceProvider = this.sourceProvider?.asProtoModel()) +fun SourceSetContainer.asProtoModel() = + SourceSetContainer( + sourceProvidersMap = scopedSourceProviders().mapValues { entry -> entry.value.asProtoModel() }, + ) fun SourceProvider.asProtoModel() = SourceProvider( @@ -242,33 +245,9 @@ fun Variant.asProtoModel( androidDsl = androidDsl, versions = versions, ), - variantSourceProvidersList = - basicAndroidProject.variantSourceProviders(this.name).map { provider -> provider.asProtoModel() }, + artifactSourcesMap = basicAndroidProject.variantArtifactSources(this), ) -/** - * The source providers AGP layers over `main` for the variant named [variantName], in the order - * AGP applies them: the build type, each product flavor, the multi-flavor provider and the - * variant's own provider. Empty when the basic model does not list the variant. - */ -fun BasicAndroidProject.variantSourceProviders(variantName: String): List { - val variant = variants.firstOrNull { it.name == variantName } ?: return emptyList() - val providers = mutableListOf() - buildTypeSourceSets - .mapNotNull { it.sourceProvider } - .firstOrNull { it.name == variant.buildType } - ?.let(providers::add) - for (flavor in variant.productFlavors) { - productFlavorSourceSets - .mapNotNull { it.sourceProvider } - .firstOrNull { it.name == flavor } - ?.let(providers::add) - } - variant.mainArtifact.multiFlavorSourceProvider?.let(providers::add) - variant.mainArtifact.variantSourceProvider?.let(providers::add) - return providers -} - fun AndroidArtifact.asProtoModel( artifactName: String, variantName: String, diff --git a/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/ScopedComponents.kt b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/ScopedComponents.kt new file mode 100644 index 0000000000..8253fdbb6f --- /dev/null +++ b/subprojects/tooling-api-impl/src/main/java/com/itsaky/androidide/tooling/impl/serial/ScopedComponents.kt @@ -0,0 +1,127 @@ +package com.itsaky.androidide.tooling.impl.serial + +import com.android.builder.model.v2.ide.AbstractArtifact +import com.android.builder.model.v2.ide.ArtifactDependencies +import com.android.builder.model.v2.ide.BasicArtifact +import com.android.builder.model.v2.ide.BasicVariant +import com.android.builder.model.v2.ide.SourceProvider +import com.android.builder.model.v2.ide.SourceSetContainer +import com.android.builder.model.v2.ide.Variant +import com.android.builder.model.v2.models.BasicAndroidProject +import com.android.builder.model.v2.models.VariantDependencies +import com.itsaky.androidide.project.AndroidModels +import com.itsaky.androidide.project.VariantArtifactSources +import com.itsaky.androidide.projects.models.ArtifactScope +import org.gradle.tooling.model.UnsupportedMethodException + +// The map keys AGP's model gives the components the single-artifact getters return. +private val UNIT_TEST_TYPE = ArtifactScope.UNIT_TEST.type +private val ANDROID_TEST_TYPE = ArtifactScope.ANDROID_TEST.type + +/** One source set's or variant's components as AGP's model reports them, before they are keyed by scope. */ +private class ComponentsByType( + val main: T?, + val testFixtures: T?, + val hostTests: Map, + val deviceTests: Map, +) { + fun keyedByScope(): Map = + buildMap { + main?.let { put(ArtifactScope.Main.key, it) } + testFixtures?.let { put(ArtifactScope.TestFixtures.key, it) } + hostTests.forEach { (type, component) -> put(ArtifactScope.HostTest(type).key, component) } + deviceTests.forEach { (type, component) -> put(ArtifactScope.DeviceTest(type).key, component) } + } +} + +/** + * AGP's per-type test map, or null on AGP 7.3 to 8.3, which predate it: the Tooling API proxies a + * missing model method by throwing [UnsupportedMethodException]. + */ +private inline fun testMap(get: () -> Map): Map? = + try { + get() + } catch (e: UnsupportedMethodException) { + null + } + +/** The single pre-map test component, as a one-entry map under [type]. */ +private fun legacyTests( + type: String, + component: T?, +): Map = component?.let { mapOf(type to it) }.orEmpty() + +/** This container's source providers by scope key. */ +fun SourceSetContainer.scopedSourceProviders(): Map = + ComponentsByType( + main = sourceProvider, + testFixtures = testFixturesSourceProvider, + hostTests = + testMap { hostTestSourceProviders } + ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestSourceProvider), + deviceTests = + testMap { deviceTestSourceProviders } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestSourceProvider), + ).keyedByScope() + +/** The dependencies of each of the variant's components by scope key. */ +fun VariantDependencies.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +private fun Variant.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +private fun BasicVariant.scopedArtifacts(): Map = + ComponentsByType( + main = mainArtifact, + testFixtures = testFixturesArtifact, + hostTests = testMap { hostTestArtifacts } ?: legacyTests(UNIT_TEST_TYPE, @Suppress("DEPRECATION") unitTestArtifact), + deviceTests = + testMap { deviceTestArtifacts } + ?: legacyTests(ANDROID_TEST_TYPE, @Suppress("DEPRECATION") androidTestArtifact), + ).keyedByScope() + +/** + * Per scope key, the source providers AGP layers over that scope's default source set for the + * variant named [variantName], in the order AGP applies them: the build type, each product flavor, + * the multi-flavor provider and the variant's own provider. Empty when the basic model does not + * list the variant. + */ +private fun BasicAndroidProject.variantLayers(variantName: String): Map> { + val variant = variants.firstOrNull { it.name == variantName } ?: return emptyMap() + val buildType = buildTypeSourceSets.firstOrNull { it.sourceProvider?.name == variant.buildType } + val flavors = variant.productFlavors.mapNotNull { flavor -> productFlavorSourceSets.firstOrNull { it.sourceProvider?.name == flavor } } + val containerLayers = (listOfNotNull(buildType) + flavors).map { it.scopedSourceProviders() } + val artifacts = variant.scopedArtifacts() + + return (containerLayers.flatMap { it.keys } + artifacts.keys).distinct().associateWith { key -> + containerLayers.mapNotNull { it[key] } + + listOfNotNull(artifacts[key]?.multiFlavorSourceProvider, artifacts[key]?.variantSourceProvider) + } +} + +/** Per scope key, the sources each of [variant]'s components adds over its default source set. */ +fun BasicAndroidProject.variantArtifactSources(variant: Variant): Map { + val generated = variant.scopedArtifacts().mapValues { (_, artifact) -> artifact.generatedSourceFolders.map { it.absolutePath } } + val layers = variantLayers(variant.name) + return (generated.keys + layers.keys).associateWith { key -> + VariantArtifactSources( + variantSourceProvidersList = layers[key].orEmpty().map { it.asProtoModel() }, + generatedSourceFolderPathsList = generated[key].orEmpty(), + ) + } +} diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/ScopedArtifactsSerializationTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/ScopedArtifactsSerializationTest.kt new file mode 100644 index 0000000000..f007686353 --- /dev/null +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/ScopedArtifactsSerializationTest.kt @@ -0,0 +1,185 @@ +package com.itsaky.androidide.tooling.impl.serial + +import com.android.builder.model.v2.ide.AbstractArtifact +import com.android.builder.model.v2.ide.AndroidArtifact +import com.android.builder.model.v2.ide.ArtifactDependencies +import com.android.builder.model.v2.ide.GraphItem +import com.android.builder.model.v2.ide.JavaArtifact +import com.android.builder.model.v2.ide.SourceProvider +import com.android.builder.model.v2.ide.SourceSetContainer +import com.android.builder.model.v2.ide.Variant +import com.android.builder.model.v2.models.VariantDependencies +import com.android.builder.model.v2.models.Versions +import com.google.common.truth.Truth.assertThat +import io.mockk.every +import io.mockk.mockk +import org.gradle.tooling.model.UnsupportedMethodException +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import java.io.File + +/** + * Every component's source providers, compile graph and generated sources reach the proto model + * keyed by scope (ADFA-7115), from AGP's per-type test maps or, on models that predate them, from + * the single-artifact getters. + */ +@Suppress("DEPRECATION") +@RunWith(JUnit4::class) +class ScopedArtifactsSerializationTest { + @Test + fun `req 2 - host and device test source providers become prefixed scope keys`() { + val container = + container( + hostTests = + mapOf( + "_unit_test_" to provider("/p/src/test/java"), + "_screenshot_test_" to provider("/p/src/screenshotTest/java"), + ), + deviceTests = mapOf("_android_test_" to provider("/p/src/androidTest/java")), + ) + + val proto = container.asProtoModel() + + assertThat(proto.sourceProvidersMap.keys) + .containsExactly("main", "host:_unit_test_", "host:_screenshot_test_", "device:_android_test_") + assertThat(proto.sourceProvidersMap.getValue("host:_screenshot_test_").javaDirsList) + .containsExactly("/p/src/screenshotTest/java") + } + + @Test + fun `req 4 - each scope keeps its own compile graph`() { + val dependencies = + dependencies( + hostTests = mapOf("_unit_test_" to artifact("junit")), + deviceTests = mapOf("_android_test_" to artifact("espresso")), + fixtures = artifact("fixtures-lib"), + ) + + val proto = dependencies.asProtoModel() + + assertThat( + proto.artifactsMap + .getValue("main") + .compileGraph.keyList, + ).containsExactly("main-lib") + assertThat( + proto.artifactsMap + .getValue("host:_unit_test_") + .compileGraph.keyList, + ).containsExactly("junit") + assertThat( + proto.artifactsMap + .getValue("device:_android_test_") + .compileGraph.keyList, + ).containsExactly("espresso") + assertThat( + proto.artifactsMap + .getValue("testFixtures") + .compileGraph.keyList, + ).containsExactly("fixtures-lib") + } + + @Test + fun `AGP 7_3 fallback - singular getters fill the same keys when the maps are unsupported`() { + val legacyContainer: SourceSetContainer = + mockk { + every { sourceProvider } returns provider("/p/src/main/java") + every { testFixturesSourceProvider } returns null + every { hostTestSourceProviders } throws UnsupportedMethodException("no hostTestSourceProviders") + every { deviceTestSourceProviders } throws UnsupportedMethodException("no deviceTestSourceProviders") + every { unitTestSourceProvider } returns provider("/p/src/test/java") + every { androidTestSourceProvider } returns provider("/p/src/androidTest/java") + } + val legacyDependencies: VariantDependencies = + mockk { + every { name } returns "debug" + every { mainArtifact } returns artifact("main-lib") + every { libraries } returns emptyMap() + every { testFixturesArtifact } returns null + every { hostTestArtifacts } throws UnsupportedMethodException("no hostTestArtifacts") + every { deviceTestArtifacts } throws UnsupportedMethodException("no deviceTestArtifacts") + every { unitTestArtifact } returns artifact("junit") + every { androidTestArtifact } returns artifact("espresso") + } + + assertThat(legacyContainer.asProtoModel().sourceProvidersMap.keys) + .containsExactly("main", "host:_unit_test_", "device:_android_test_") + assertThat(legacyDependencies.asProtoModel().artifactsMap.keys) + .containsExactly("main", "host:_unit_test_", "device:_android_test_") + } + + @Test + fun `req 2 - each component's generated source folders are kept under its key`() { + val unitTest = generating("/p/build/generated/ksp/debugUnitTest") + val androidTest = generating("/p/build/generated/ksp/debugAndroidTest") + val variant: Variant = + mockk(relaxed = true) { + every { name } returns "debug" + every { mainArtifact } returns generating("/p/build/generated/ksp/debug") + every { testFixturesArtifact } returns null + every { hostTestArtifacts } returns mapOf("_unit_test_" to unitTest) + every { deviceTestArtifacts } returns mapOf("_android_test_" to androidTest) + } + val versions: Versions = mockk { every { agp } returns "8.8.2" } + + val proto = variant.asProtoModel(mockk(relaxed = true), mockk(relaxed = true), mockk(relaxed = true), versions) + + assertThat(proto.artifactSourcesMap.getValue("main").generatedSourceFolderPathsList) + .containsExactly("/p/build/generated/ksp/debug") + assertThat(proto.artifactSourcesMap.getValue("host:_unit_test_").generatedSourceFolderPathsList) + .containsExactly("/p/build/generated/ksp/debugUnitTest") + assertThat(proto.artifactSourcesMap.getValue("device:_android_test_").generatedSourceFolderPathsList) + .containsExactly("/p/build/generated/ksp/debugAndroidTest") + } + + /** An artifact whose only generated source folder is [dir]. */ + private inline fun generating(dir: String): T = + mockk(relaxed = true) { every { generatedSourceFolders } returns listOf(File(dir)) } + + private fun container( + hostTests: Map = emptyMap(), + deviceTests: Map = emptyMap(), + fixtures: SourceProvider? = null, + ): SourceSetContainer = + mockk { + every { sourceProvider } returns provider("/p/src/main/java") + every { testFixturesSourceProvider } returns fixtures + every { hostTestSourceProviders } returns hostTests + every { deviceTestSourceProviders } returns deviceTests + } + + private fun dependencies( + hostTests: Map = emptyMap(), + deviceTests: Map = emptyMap(), + fixtures: ArtifactDependencies? = null, + ): VariantDependencies = + mockk { + every { name } returns "debug" + every { mainArtifact } returns artifact("main-lib") + every { libraries } returns emptyMap() + every { testFixturesArtifact } returns fixtures + every { hostTestArtifacts } returns hostTests + every { deviceTestArtifacts } returns deviceTests + } + + private fun provider(javaDir: String): SourceProvider = + mockk { + every { javaDirectories } returns listOf(File(javaDir)) + every { kotlinDirectories } returns emptyList() + every { resDirectories } returns emptyList() + } + + private fun artifact(key: String): ArtifactDependencies { + val item: GraphItem = + mockk { + every { this@mockk.key } returns key + every { requestedCoordinates } returns null + every { dependencies } returns emptyList() + } + return mockk { + every { compileDependencies } returns listOf(item) + every { unresolvedDependencies } returns emptyList() + } + } +} diff --git a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/VariantSourceProvidersTest.kt b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/VariantSourceProvidersTest.kt index 36094e9ada..7334b30f57 100644 --- a/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/VariantSourceProvidersTest.kt +++ b/subprojects/tooling-api-impl/src/test/java/com/itsaky/androidide/tooling/impl/serial/VariantSourceProvidersTest.kt @@ -4,6 +4,7 @@ import com.android.builder.model.v2.ide.BasicArtifact import com.android.builder.model.v2.ide.BasicVariant import com.android.builder.model.v2.ide.SourceProvider import com.android.builder.model.v2.ide.SourceSetContainer +import com.android.builder.model.v2.ide.Variant import com.android.builder.model.v2.models.BasicAndroidProject import com.google.common.truth.Truth.assertThat import io.mockk.every @@ -11,78 +12,132 @@ import io.mockk.mockk import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 +import java.io.File /** - * [variantSourceProviders] picks, from the basic model, exactly the providers AGP layers over - * `main` for one variant, in AGP's order. Build-type and flavor containers are matched by the - * name AGP gives their provider, so the other build type's container never leaks in. + * [variantArtifactSources] picks, per scope, exactly the providers AGP layers over that scope's + * default source set for one variant, in AGP's order. Build-type and flavor containers are matched + * by the name AGP gives their main provider, so the other build type's container never leaks in. */ @RunWith(JUnit4::class) class VariantSourceProvidersTest { - private val debug = provider("debug") - private val release = provider("release") - private val free = provider("free") - private val paid = provider("paid") - private val multiFlavor = provider("free") - private val freeDebug = provider("freeDebug") + private val debug = container("debug", unitTest = "testDebug") + private val release = container("release", unitTest = "testRelease") + private val free = container("free", unitTest = "testFree") + private val paid = container("paid", unitTest = "testPaid") @Test - fun `layers build type, flavor, multi-flavor and variant providers in AGP order`() { + fun `req 1 - main layers build type, flavor, multi-flavor and variant providers in AGP order`() { val project = - project( - variant("freeDebug", buildType = "debug", flavors = listOf("free"), multi = multiFlavor, own = freeDebug), - ) + project(basicVariant("freeDebug", buildType = "debug", flavors = listOf("free"), main = artifact("freeMulti", "freeDebug"))) - assertThat(project.variantSourceProviders("freeDebug")) - .containsExactly(debug, free, multiFlavor, freeDebug) + val sources = project.variantArtifactSources(variant("freeDebug")) + + assertThat(sources.getValue("main").variantSourceProvidersList.map { it.javaDirsList.single() }) + .containsExactly(dir("debug"), dir("free"), dir("freeMulti"), dir("freeDebug")) .inOrder() } @Test - fun `a variant without flavors carries only its build type and its own provider`() { - val own = provider("debug-own") - val project = project(variant("debug", buildType = "debug", flavors = emptyList(), multi = null, own = own)) + fun `req 1 - a variant without flavors carries only its build type and its own provider`() { + val project = project(basicVariant("debug", buildType = "debug", flavors = emptyList(), main = artifact(null, "debug-own"))) + + val sources = project.variantArtifactSources(variant("debug")) - assertThat(project.variantSourceProviders("debug")) - .containsExactly(debug, own) + assertThat(sources.getValue("main").variantSourceProvidersList.map { it.javaDirsList.single() }) + .containsExactly(dir("debug"), dir("debug-own")) .inOrder() } @Test - fun `a variant the basic model does not list yields no providers`() { - val project = project(variant("debug", buildType = "debug", flavors = emptyList(), multi = null, own = null)) + fun `req 2 - a test artifact carries its own variant layers`() { + val project = + project( + basicVariant( + "freeDebug", + buildType = "debug", + flavors = listOf("free"), + main = artifact(null, null), + unitTest = artifact("testFreeMulti", "testFreeDebug"), + ), + ) + + val sources = project.variantArtifactSources(variant("freeDebug")) - assertThat(project.variantSourceProviders("release")).isEmpty() + assertThat(sources.getValue("host:_unit_test_").variantSourceProvidersList.map { it.javaDirsList.single() }) + .containsExactly(dir("testDebug"), dir("testFree"), dir("testFreeMulti"), dir("testFreeDebug")) + .inOrder() } - private fun provider(name: String): SourceProvider = mockk { every { this@mockk.name } returns name } + @Test + fun `req 1 - a variant the basic model does not list has no variant layers`() { + val project = project(basicVariant("debug", buildType = "debug", flavors = emptyList(), main = artifact(null, null))) + + val sources = project.variantArtifactSources(variant("release")) - private fun container(provider: SourceProvider): SourceSetContainer = mockk { every { sourceProvider } returns provider } + assertThat(sources.values.flatMap { it.variantSourceProvidersList }).isEmpty() + } - private fun variant( + private fun dir(name: String) = "/p/src/$name/java" + + private fun provider(name: String): SourceProvider = + mockk { + every { this@mockk.name } returns name + every { javaDirectories } returns listOf(File(dir(name))) + every { kotlinDirectories } returns emptyList() + every { resDirectories } returns emptyList() + } + + private fun container( + name: String, + unitTest: String, + ): SourceSetContainer = + mockk { + every { sourceProvider } returns provider(name) + every { testFixturesSourceProvider } returns null + every { hostTestSourceProviders } returns mapOf("_unit_test_" to provider(unitTest)) + every { deviceTestSourceProviders } returns emptyMap() + } + + private fun artifact( + multi: String?, + own: String?, + ): BasicArtifact = + mockk { + every { multiFlavorSourceProvider } returns multi?.let(::provider) + every { variantSourceProvider } returns own?.let(::provider) + } + + private fun basicVariant( name: String, buildType: String, flavors: List, - multi: SourceProvider?, - own: SourceProvider?, - ): BasicVariant { - val artifact: BasicArtifact = - mockk { - every { multiFlavorSourceProvider } returns multi - every { variantSourceProvider } returns own - } - return mockk { + main: BasicArtifact, + unitTest: BasicArtifact? = null, + ): BasicVariant = + mockk { every { this@mockk.name } returns name every { this@mockk.buildType } returns buildType every { productFlavors } returns flavors - every { mainArtifact } returns artifact + every { mainArtifact } returns main + every { testFixturesArtifact } returns null + every { hostTestArtifacts } returns unitTest?.let { mapOf("_unit_test_" to it) }.orEmpty() + every { deviceTestArtifacts } returns emptyMap() + } + + /** A full-model variant with no generated sources, so only the basic model's layers show. */ + private fun variant(name: String): Variant = + mockk(relaxed = true) { + every { this@mockk.name } returns name + every { testFixturesArtifact } returns null + every { hostTestArtifacts } returns emptyMap() + every { deviceTestArtifacts } returns emptyMap() } - } private fun project(vararg variants: BasicVariant): BasicAndroidProject = mockk { every { this@mockk.variants } returns variants.toList() - every { buildTypeSourceSets } returns listOf(container(release), container(debug)) - every { productFlavorSourceSets } returns listOf(container(paid), container(free)) + every { buildTypeSourceSets } returns listOf(release, debug) + every { productFlavorSourceSets } returns listOf(paid, free) } } diff --git a/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt b/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt index c515d4c475..698c7ea4f3 100644 --- a/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt +++ b/subprojects/tooling-api/src/main/java/com/itsaky/androidide/tooling/api/sync/ProjectSyncHelper.kt @@ -51,7 +51,7 @@ object ProjectSyncHelper { * differs from this one discards the sync files and forces a full sync. The models are * produced and consumed only by the IDE and hold no user data, so discarding them is safe. */ - const val SYNC_META_VERSION = "2" + const val SYNC_META_VERSION = "3" private val logger = LoggerFactory.getLogger(ProjectSyncHelper::class.java)