Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bgp-metro-res-duplicates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@callstack/react-native-brownfield': patch
---

fix: the AAR build no longer fails with duplicate resources when an embedded library ships the same drawables Metro generates for the app's bundle. Metro's copy wins.
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import com.callstack.react.brownfield.exceptions.NameSpaceNotFound
import com.callstack.react.brownfield.processors.VariantHelper
import com.callstack.react.brownfield.utils.Extension
import com.callstack.react.brownfield.utils.Utils
import com.callstack.react.brownfield.utils.capitalized
import org.gradle.api.GradleException
import com.callstack.react.brownfield.utils.directoryGetter
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.DirectoryProperty
Expand Down Expand Up @@ -57,16 +56,9 @@ object RNSourceSets {
// 2. Use the onVariants block to wire RN bundle outputs via the Variant Sources API
componentsExtension.onVariants { variant ->
val variantName = variant.name
val bundledAssetsVariantName =
VariantHelper.getBundledAssetsVariantName(
variantName = variantName,
buildTypeName = variant.buildType,
isDebuggable = variant.debuggable,
)
val capitalizedBundledAssetsVariantName = bundledAssetsVariantName.capitalized()
val appProject = getAppProject()

val jsBundleTaskName = "createBundle${capitalizedBundledAssetsVariantName}JsAndAssets"
val jsBundleTaskName = VariantHelper.getMetroBundleTaskName(variant)

/**
* Wire the bundle task's own `jsBundleDir`/`resourcesDir` outputs as *generated*
Expand All @@ -89,12 +81,7 @@ object RNSourceSets {

/**
* Wires `taskName`'s `getterName` output (expected to be a `DirectoryProperty`) as a
* generated source directory for `sources`.
*
* Resolving the task by name (rather than importing its class) keeps this plugin from
* depending on RNGP's/expo-updates' internal task types. If the task, or its expected output
* property, isn't there, this fails the build immediately with a clear message instead of
* silently producing an empty/stale source directory.
* generated source directory for `sources`. See [directoryGetter] for the checks.
*/
private fun wireGeneratedSourceDirectory(
appProject: Project,
Expand All @@ -104,27 +91,7 @@ object RNSourceSets {
) {
if (sources == null) return

val task =
appProject.tasks.findByName(taskName)
?: throw GradleException(
"brownfield: expected task '$taskName' was not found in project " +
"'${appProject.path}'. Check that the plugin producing it is applied there.",
)

val getter =
runCatching { task.javaClass.getMethod(getterName) }.getOrElse {
throw GradleException(
"brownfield: task '$taskName' (${task.javaClass.name}) does not expose " +
"'$getterName()'. The plugin that registers it most likely changed its " +
"API; the brownfield Gradle plugin needs updating to match.",
it,
)
}

check(DirectoryProperty::class.java.isAssignableFrom(getter.returnType)) {
"brownfield: '$taskName.$getterName()' no longer returns a DirectoryProperty."
}

val getter = directoryGetter(appProject, taskName, getterName)
val taskProvider = appProject.tasks.named(taskName)
sources.addGeneratedSourceDirectory(taskProvider) { t -> getter.invoke(t) as DirectoryProperty }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import com.android.ide.common.resources.ResourceSet
import com.callstack.react.brownfield.shared.ExplodeAarTask
import com.callstack.react.brownfield.shared.GradleILogger
import com.callstack.react.brownfield.utils.AndroidArchiveLibrary
import com.callstack.react.brownfield.utils.Extension
import com.callstack.react.brownfield.utils.capitalized
import com.callstack.react.brownfield.utils.directoryGetter
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.ConfigurableFileCollection
Expand Down Expand Up @@ -198,6 +200,21 @@ private class LibraryResWriter(
}
}

/**
* Some libraries commit the drawables Metro generates for their JS assets to their own `res`, and
* the app's bundle writes the same files to `generated/res/react`. Both end up as generated res of
* this module, where AGP fails on the duplicates, so Metro's copy is treated as the module's own and
* wins. Reading the bundle task's output also orders the copy after it, and keys the cache on it.
*/
internal fun wireMetroResDir(
task: CopyExplodedResTask,
appProject: Project,
bundleTaskName: String,
) {
val getter = directoryGetter(appProject, bundleTaskName, "getResourcesDir")
task.moduleResDirs.from(appProject.tasks.named(bundleTaskName).flatMap { getter.invoke(it) as DirectoryProperty })
}

object ResourceTaskProcessor {
private const val RES_VALUES_OFF_BY_DEFAULT_SINCE_AGP = 9

Expand All @@ -210,6 +227,7 @@ object ResourceTaskProcessor {
val capitalized = variant.name.capitalized()
val resDirs = aarLibraries.map { it.getResDir() }
val buildDir = project.layout.buildDirectory.get().asFile
val appProject = project.rootProject.project(project.extensions.getByType(Extension::class.java).appProjectName)
val copyResTask =
project.tasks.register(
"copyExplodedResFor$capitalized",
Expand All @@ -223,6 +241,7 @@ object ResourceTaskProcessor {
}
variant.sources.res?.static?.let { static -> task.moduleResDirs.from(static.map { layers -> layers.flatten() }) }
task.libraryOrder.set(aarLibraries.map { it.getExplodedAarRootDir().relativeTo(buildDir).invariantSeparatorsPath })
wireMetroResDir(task, appProject, VariantHelper.getMetroBundleTaskName(variant))
task.dependsOn(explodeTask)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.callstack.react.brownfield.processors

import com.android.build.api.variant.LibraryVariant
import com.callstack.react.brownfield.utils.capitalized
import org.gradle.api.Project
import org.gradle.api.Task
Expand Down Expand Up @@ -39,6 +40,12 @@ object VariantHelper {
}
}

/** RNGP's `createBundle<Variant>JsAndAssets` task in the app project for [variant]. */
fun getMetroBundleTaskName(variant: LibraryVariant): String {
val bundledAssetsVariantName = getBundledAssetsVariantName(variant.name, variant.buildType, variant.debuggable)
return "createBundle${bundledAssetsVariantName.capitalized()}JsAndAssets"
}

fun getExpoUpdatesResourcesTaskName(variantName: String): String {
return "create${variantName.capitalized()}UpdatesResources"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.callstack.react.brownfield.utils

import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import java.lang.reflect.Method

/**
* Finds `taskName`'s `getterName()` that returns a `DirectoryProperty`. Resolving the task by name
* (rather than importing its class) keeps this plugin from depending on RNGP's/expo-updates'
* internal task types. If the task, or the property, isn't there, this fails the build with a
* clear message instead of silently producing an empty or stale directory.
*/
internal fun directoryGetter(
appProject: Project,
taskName: String,
getterName: String,
): Method {
val task =
appProject.tasks.findByName(taskName)
?: throw GradleException(
"brownfield: expected task '$taskName' was not found in project " +
"'${appProject.path}'. Check that the plugin producing it is applied there.",
)

val getter =
runCatching { task.javaClass.getMethod(getterName) }.getOrElse {
throw GradleException(
"brownfield: task '$taskName' (${task.javaClass.name}) does not expose " +
"'$getterName()'. The plugin that registers it most likely changed its " +
"API; the brownfield Gradle plugin needs updating to match.",
it,
)
}

check(DirectoryProperty::class.java.isAssignableFrom(getter.returnType)) {
"brownfield: '$taskName.$getterName()' no longer returns a DirectoryProperty."
}
return getter
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ class CopyExplodedResTaskTest {
assertTrue(!File(out, "drawable/logo.xml").exists(), "the library's drawable overrides the module's")
}

@Test
fun `drops a library's copy of a Metro asset`() {
val metro = File(tempDir, "app/generated/res/react/release")
File(metro, "drawable-mdpi").mkdirs()
File(metro, "drawable-mdpi/node_modules_sdk_assets_icon.png").writeBytes(byteArrayOf(1))
val lib = libraryRes("flagship-sdk", "")
File(lib, "drawable-mdpi-v4").mkdirs()
File(lib, "drawable-mdpi-v4/node_modules_sdk_assets_icon.png").writeBytes(byteArrayOf(2))
File(lib, "drawable-mdpi-v4/sdk_only.png").writeBytes(byteArrayOf(3))

val out = runCopy(lib, moduleResDirs = listOf(metro))

assertTrue(!File(out, "drawable-mdpi-v4/node_modules_sdk_assets_icon.png").exists())
assertTrue(File(out, "drawable-mdpi-v4/sdk_only.png").exists())
}

@Test
fun `matches the module's qualifiers with the normalized ones of an AAR`() {
val module = File(tempDir, "module/res")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.callstack.react.brownfield.processors

import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.tasks.OutputDirectory
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue

abstract class FakeBundleTask : DefaultTask() {
@get:OutputDirectory
abstract val resourcesDir: DirectoryProperty
}

class MetroResDirWiringTest {
@TempDir
lateinit var tempDir: File

@Test
fun `treats Metro's res output as the module's own and runs after the bundle`() {
val root = ProjectBuilder.builder().withProjectDir(tempDir).build()
val app = ProjectBuilder.builder().withName("app").withParent(root).build()
val lib = ProjectBuilder.builder().withName("BrownfieldLib").withParent(root).build()
val metroDir = File(tempDir, "app/build/generated/res/react/release")
val bundle =
app.tasks.register("createBundleReleaseJsAndAssets", FakeBundleTask::class.java) {
it.resourcesDir.set(metroDir)
}
val copy = lib.tasks.register("copyExplodedResForRelease", CopyExplodedResTask::class.java).get()

wireMetroResDir(copy, app, "createBundleReleaseJsAndAssets")

assertEquals(setOf(metroDir), copy.moduleResDirs.files)
assertTrue(bundle.get() in copy.taskDependencies.getDependencies(copy))
}
}
Loading