diff --git a/.changeset/aar-so-selection.md b/.changeset/aar-so-selection.md new file mode 100644 index 00000000..73b9308f --- /dev/null +++ b/.changeset/aar-so-selection.md @@ -0,0 +1,5 @@ +--- +'@callstack/react-native-brownfield': minor +--- + +fix: pick the right `.so` files for the Android AAR. With `useStrippedSoFiles = false`, the AAR now has `libappmodules.so` and `libreact_codegen_*.so`. Before this fix, those libs were missing and host apps crashed. The AAR also stops embedding the `.so` files of Maven dependencies. The host already gets those through the POM, so its build no longer fails with `2 files found with path 'lib//.so'`. If your app module builds or ships a `.so` of its own, list it in `reactBrownfield.dynamicLibs`, which is back. The build lists the `.so` files it left out in `/build/reports/brownfield//skipped-so.txt`. After upgrading, check that file: it lists the `.so` files that used to be in the AAR and now aren't. diff --git a/gradle-plugins/react/README.md b/gradle-plugins/react/README.md index 13d58e90..60886b20 100644 --- a/gradle-plugins/react/README.md +++ b/gradle-plugins/react/README.md @@ -189,14 +189,31 @@ The plugin supports Expo projects out of the box. Publishing the AAR to Maven Lo **Dynamic libs** -By default only `libappmodules.so` and `libreact_codegen*.so` are bundled with the aar. If you would like to bundle other dynamic libs, you can define those in the `reactBrownfield` extension as shown below: +The AAR contains two kinds of native libs (`.so` files): + +- the app module's own libs: `libappmodules.so` and `libreact_codegen_*.so` +- the libs of every library you embed + +The `.so` files of Maven dependencies stay out of the AAR. The host app gets them through the AAR's POM, together with the rest of those libraries. Embedding them too would give the host two copies and fail its build. If you set `experimentalIncludeTransitiveDependencies = false`, the POM doesn't list those dependencies, so the host app must declare them itself. The same goes for any dependency the POM can't list: one with no version (managed by a BOM) or a dynamic version, one declared only for a flavor or build type, or one declared only in the app module. The host app needs that library's classes as well, so it has to declare the library either way, and that also brings its `.so` files. A `.so` from a local file dependency has no Maven artifact the host could declare; add it to `dynamicLibs`. + +The AAR only has the ABIs (CPU architectures) your app module builds. If the app module uses `abiFilters`, ABIs it leaves out are dropped from the embedded libraries too. A device would otherwise pick an ABI folder that has no `libappmodules.so`, and the app would crash. + +`useStrippedSoFiles` (default `true`) picks which copy the plugin starts from: the app module's stripped output or its unstripped output. It does not change which libs are embedded. AGP still runs its own strip step on the AAR's native libs during packaging. + +To change the set: + +- `dynamicLibs` adds libs, by exact file name. Use it for a `.so` the host app cannot get any other way: one your app module builds or ships itself (for example from `app/src/main/jniLibs`), or one from a dependency the published AAR does not declare. +- `ignoreEmbeddedLibs` keeps libs out. A lib is left out when its name contains an entry. It never removes `libappmodules.so` or `libreact_codegen_*.so`. It does win over `dynamicLibs`, and the build warns when that happens. ```kts reactBrownfield { - dynamicLibs = listOf("libreact-native-mmkv.so", "libreact-native-fs-turbo.so") + dynamicLibs = listOf("libmy-prebuilt.so") + ignoreEmbeddedLibs = listOf("libdatadog-ndk.so") } ``` +If the host app crashes with `dlopen failed: library "libX.so" not found`, open `/build/reports/brownfield//skipped-so.txt`. It lists every `.so` that was left out of the AAR and why. The build also prints a `Brownfield: left … out of the AAR` line, but only when that task runs, not when Gradle reuses a cached result. If the missing lib is there and the host can't get it from a Maven dependency, add it to `dynamicLibs`. +
**Flavored Android Builds** diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/plugin/RNBrownfieldPlugin.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/plugin/RNBrownfieldPlugin.kt index 6e955f0a..4e3f27bf 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/plugin/RNBrownfieldPlugin.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/plugin/RNBrownfieldPlugin.kt @@ -277,7 +277,7 @@ class RNBrownfieldPlugin : Plugin { /** ===== jniLibsProcessor ===== */ val jniLibsProcessor = JNILibsProcessor(project) - jniLibsProcessor.processJniLibs(aarLibraries, variant) + jniLibsProcessor.processJniLibs(aarLibraries, variant, explodeTask) /** ===== proguardProcessor ===== */ val proguardProcessor = ProguardProcessor(project) diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/processors/JNILibsProcessor.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/processors/JNILibsProcessor.kt index d76bb485..16be82f6 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/processors/JNILibsProcessor.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/processors/JNILibsProcessor.kt @@ -1,28 +1,27 @@ package com.callstack.react.brownfield.processors import com.android.build.api.variant.LibraryVariant -import com.callstack.react.brownfield.shared.Logging import com.callstack.react.brownfield.utils.AndroidArchiveLibrary import com.callstack.react.brownfield.utils.Extension import com.callstack.react.brownfield.utils.capitalized import org.gradle.api.DefaultTask import org.gradle.api.Project +import org.gradle.api.Task import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.TaskProvider import java.io.File -import kotlin.collections.component1 -import kotlin.collections.component2 /** * Below contains a list of dynamic libs which we should not embed @@ -37,126 +36,246 @@ val IGNORE_EMBEDDED_LIBS = "libreactnative.so", ) +private val ABIS = listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86") + +private const val APP_MODULES_LIB = "libappmodules.so" + +internal enum class SkipReason { IGNORED, NOT_EMBEDDED } + +/** + * @property copies source file for each `/` that goes into the AAR + * @property unmatchedDynamicLibs dynamicLibs entries that match no file in the app module's output + * @property skipped every lib name that no ABI copies, with why + * @property ignoredDynamicLibs dynamicLibs entries dropped because an ignore entry matches them + * @property excludedAbis ABIs the embedded AARs ship but the app module did not build + */ +internal data class JniLibsPlan( + val copies: Map, + val unmatchedDynamicLibs: Set, + val skipped: Map, + val ignoredDynamicLibs: Set = emptySet(), + val excludedAbis: Set = emptySet(), +) + +private fun isAppOwned(name: String) = name == APP_MODULES_LIB || (name.startsWith("libreact_codegen_") && name.endsWith(".so")) + +private fun isIgnored( + name: String, + ignoredLibs: List, +) = ignoredLibs.any { entry -> name == entry || name.contains(entry) } + +private fun libNames(dir: File?): List = dir?.listFiles()?.filter { it.isFile }?.map { it.name }.orEmpty() + +/** + * Picks the .so files for the AAR: the app module's own libs, the libs the embedded libraries + * ship, and [dynamicLibs], minus [ignoredLibs]. Libs that only come from Maven dependencies stay + * out, because the host app gets them through the published POM. + */ +internal fun planJniLibs( + aarJniDirs: List, + appNativeLibsDir: File?, + ignoredLibs: List, + dynamicLibs: List, +): JniLibsPlan { + val copies = linkedMapOf() + val matchedDynamicLibs = mutableSetOf() + val candidates = mutableMapOf() + val ignoredDynamicLibs = mutableSetOf() + + // An ABI folder without libappmodules.so crashes on devices that pick it, so follow the app + // module's ABIs (it may use abiFilters) and only fall back to all of them when it built none. + val appAbis = ABIS.filter { abi -> appNativeLibsDir?.let { File(it, abi).isDirectory } == true } + val abis = appAbis.ifEmpty { ABIS } + val excludedAbis = ABIS.filter { abi -> abi !in abis && aarJniDirs.any { File(it, abi).isDirectory } }.toSet() + + for (abi in abis) { + val appAbiDir = appNativeLibsDir?.let { File(it, abi) } + val appNames = libNames(appAbiDir).toSet() + + val embedded = linkedMapOf() + aarJniDirs.forEach { jniDir -> + val abiDir = File(jniDir, abi) + libNames(abiDir).forEach { name -> embedded.putIfAbsent(name, File(abiDir, name)) } + } + val extra = dynamicLibs.filter { it in appNames } + matchedDynamicLibs += extra + ignoredDynamicLibs += extra.filter { isIgnored(it, ignoredLibs) } + + val wanted = appNames.filter(::isAppOwned) + (embedded.keys + extra).filterNot { isIgnored(it, ignoredLibs) } + wanted.forEach { name -> + copies["$abi/$name"] = appAbiDir?.let { File(it, name) }?.takeIf { it.isFile } ?: embedded.getValue(name) + } + + (appNames + embedded.keys).filterNot { it in wanted }.forEach { name -> + val reason = if (isIgnored(name, ignoredLibs)) SkipReason.IGNORED else SkipReason.NOT_EMBEDDED + // IGNORED wins: once a name is ignored in one ABI it is ignored everywhere. + if (candidates[name] != SkipReason.IGNORED) candidates[name] = reason + } + } + + val copiedNames = copies.keys.map { it.substringAfter('/') }.toSet() + return JniLibsPlan( + copies = copies, + unmatchedDynamicLibs = dynamicLibs.toSet() - matchedDynamicLibs, + skipped = candidates.filterKeys { it !in copiedNames }.toSortedMap(), + ignoredDynamicLibs = ignoredDynamicLibs, + excludedAbis = excludedAbis, + ) +} + +internal fun planWarnings(plan: JniLibsPlan): List = + plan.unmatchedDynamicLibs.map { entry -> + "Brownfield: dynamicLibs entry '$entry' matches no .so file in the app module's native output." + } + + plan.ignoredDynamicLibs.map { name -> + "Brownfield: dynamicLibs entry '$name' is not in the AAR because an ignore entry matches it. " + + "Remove that entry from ignoreEmbeddedLibs to embed it." + } + +/** + * One line naming the libs no embedded library ships, or null when there are none. Ignored libs + * are left out: they are skipped on purpose and would only add noise on every build. + */ +internal fun skippedSummary( + plan: JniLibsPlan, + reportFile: File?, +): String? { + val names = plan.skipped.filterValues { it == SkipReason.NOT_EMBEDDED }.keys.sorted() + if (names.isEmpty()) return null + val details = reportFile?.let { " Details: ${it.absolutePath}" }.orEmpty() + return "Brownfield: left ${names.size} .so file(s) out of the AAR because no embedded library ships them: " + + "${names.joinToString(", ")}. If one comes from a Maven dependency, the host app gets it through the POM. " + + "If not (for example, your app module builds or ships it), add it to reactBrownfield.dynamicLibs.$details" +} + +internal data class AppNativeLibsSource(val relativeDir: String, val producerTaskName: String) + +internal fun appNativeLibsSource( + variantName: String, + useStrippedSoFiles: Boolean, +): AppNativeLibsSource { + val capitalized = variantName.capitalized() + return if (useStrippedSoFiles) { + val task = "strip${capitalized}DebugSymbols" + AppNativeLibsSource("intermediates/stripped_native_libs/$variantName/$task/out/lib", task) + } else { + val task = "merge${capitalized}NativeLibs" + AppNativeLibsSource("intermediates/merged_native_libs/$variantName/$task/out/lib", task) + } +} + @CacheableTask abstract class ProcessAndCopyJniLibsTask : DefaultTask() { @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val aarJniDirs: ConfigurableFileCollection - @get:InputDirectory + // @InputFiles rather than @InputDirectory: a variant without native code has no such dir, + // and @InputDirectory would fail validation before the task can run. + @get:InputFiles @get:Optional @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val strippedLibsDir: DirectoryProperty + abstract val appNativeLibsDir: DirectoryProperty @get:Input - abstract val useStrippedSoFiles: Property + abstract val extraIgnoredLibs: ListProperty @get:Input - abstract val extraIgnoredLibs: ListProperty + abstract val dynamicLibs: ListProperty @get:OutputDirectory abstract val outputDirectory: DirectoryProperty + // A declared output, so it is restored on cache hits when nothing is logged. + @get:OutputFile + abstract val skippedReportFile: RegularFileProperty + @TaskAction fun execute() { val outDir = outputDirectory.get().asFile - // Clear out old data to ensure clean, reproducible builds outDir.deleteRecursively() outDir.mkdirs() - val existingJNILibs = - listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86") - .associateWith { mutableListOf() } - .toMutableMap() - - // 1. Scan and process duplicate libs from AAR paths - aarJniDirs.forEach { jniDir -> - if (jniDir.exists()) { - processNestedLibs(jniDir.listFiles(), existingJNILibs) - - // If not using stripped files, copy the unstripped ones directly to our output - if (!useStrippedSoFiles.get()) { - jniDir.copyRecursively(outDir, overwrite = true) - } - } + val appDir = appNativeLibsDir.orNull?.asFile + if (appDir != null && !appDir.exists()) { + logger.warn( + "Brownfield: $appDir does not exist, so libappmodules.so and libreact_codegen_*.so " + + "were not found and are not in the AAR.", + ) } - // 2. If using stripped files, copy targeted files from the stripped directory - if (useStrippedSoFiles.get() && strippedLibsDir.isPresent) { - copyStrippedSoLibs(outDir, existingJNILibs) - } - } + val plan = + planJniLibs( + aarJniDirs.files.toList(), + appDir, + IGNORE_EMBEDDED_LIBS + extraIgnoredLibs.getOrElse(emptyList()), + dynamicLibs.getOrElse(emptyList()), + ) - private fun copyStrippedSoLibs( - outDir: File, - existingJNILibs: MutableMap>, - ) { - val fromDir = strippedLibsDir.get().asFile - if (!fromDir.exists()) return + plan.copies.forEach { (path, source) -> source.copyTo(File(outDir, path), overwrite = true) } - existingJNILibs.keys.forEach { arch -> - copyArchStrippedSoLibs(fromDir, outDir, arch) + writeReport(plan) + val reportFile = skippedReportFile.get().asFile + skippedSummary(plan, reportFile)?.let { logger.lifecycle(it) } + plan.skipped.forEach { (name, reason) -> logger.info("Brownfield: skipped $name ($reason)") } + planWarnings(plan).forEach { logger.warn(it) } + if (plan.excludedAbis.isNotEmpty()) { + logger.info("Brownfield: left out ABIs the app module did not build: ${plan.excludedAbis.sorted().joinToString(", ")}") } } - private fun copyArchStrippedSoLibs( - fromDir: File, - outDir: File, - arch: String, - ) { - val sourceArchDir = File(fromDir, arch) - if (!sourceArchDir.exists()) return - - val destArchDir = File(outDir, arch).apply { mkdirs() } - sourceArchDir.listFiles()?.forEach { file -> - copyIfAllowed(file, destArchDir) - } + private fun writeReport(plan: JniLibsPlan) { + val reportFile = skippedReportFile.get().asFile + reportFile.parentFile.mkdirs() + val lines = + if (plan.skipped.isEmpty()) { + listOf("No .so files were left out.") + } else { + listOfNotNull(skippedSummary(plan, null)) + plan.skipped.map { (name, reason) -> "$name: $reason" } + } + reportFile.writeText(lines.joinToString("\n", postfix = "\n")) } +} - private fun copyIfAllowed( - file: File, - destArchDir: File, - ) { - val name = file.name - if (!matchesAllowedLib(name)) return +internal fun wireAarJniDirs( + task: ProcessAndCopyJniLibsTask, + jniDirs: List, + explodeTask: TaskProvider, +) { + // The dirs are plain paths, so Gradle can't infer who fills them; without this the task can + // run before the AARs are unpacked and drop every embedded lib. + task.aarJniDirs.setFrom(jniDirs) + task.aarJniDirs.builtBy(explodeTask) +} - try { - file.copyTo(File(destArchDir, name), overwrite = true) - } catch (e: java.io.IOException) { - Logging.error("Failed to copy $name: ${e.message}", e.cause) - } - } +internal fun configureProcessJniTask( + task: ProcessAndCopyJniLibsTask, + project: Project, + appProject: Project, + projectExt: Extension, + variantName: String, + jniDirs: List, + explodeTask: TaskProvider, +) { + val source = appNativeLibsSource(variantName, projectExt.useStrippedSoFiles) - private fun matchesAllowedLib(name: String): Boolean { - val isCodegenLib = name.startsWith("libreact_codegen_") && name.endsWith(".so") - val ignoredLibs = IGNORE_EMBEDDED_LIBS + extraIgnoredLibs.getOrElse(emptyList()) - val isIgnoredLib = ignoredLibs.any { lib -> name == lib || name.contains(lib) } - return name == "libappmodules.so" || isCodegenLib || !isIgnoredLib - } + task.extraIgnoredLibs.set(projectExt.ignoreEmbeddedLibs) + task.dynamicLibs.set(projectExt.dynamicLibs) + wireAarJniDirs(task, jniDirs, explodeTask) + task.appNativeLibsDir.set(appProject.layout.buildDirectory.dir(source.relativeDir)) + task.skippedReportFile.set(project.layout.buildDirectory.file("reports/brownfield/$variantName/skipped-so.txt")) - private fun processNestedLibs( - files: Array?, - existingJNILibs: MutableMap>, - ) { - files?.forEach { folder -> - val libFiles = folder.listFiles() ?: return@forEach - val libList = existingJNILibs[folder.name] ?: return@forEach - - libFiles.forEach { file -> - if (file.name in libList) { - file.delete() - } else { - libList.add(file.name) - } - } - } - } + task.dependsOn( + "${appProject.path}:${source.producerTaskName}", + "${project.path}:generateCodegenSchemaFromJavaScript", + ) } class JNILibsProcessor(val project: Project) { fun processJniLibs( aarLibraries: Collection, variant: LibraryVariant, + explodeTask: TaskProvider, ) { val variantName = variant.name val capitalizedVariantName = variantName.capitalized() @@ -165,25 +284,8 @@ class JNILibsProcessor(val project: Project) { val processJniTask = project.tasks.register("processCustomJniLibsFor$capitalizedVariantName", ProcessAndCopyJniLibsTask::class.java) { - it.useStrippedSoFiles.set(projectExt.useStrippedSoFiles) - it.extraIgnoredLibs.set(projectExt.ignoreEmbeddedLibs) - - val jniDirs = - aarLibraries.map { aarLib -> - aarLib.getJniDir() - } - - it.aarJniDirs.setFrom(jniDirs) - - val fromDirProvider = - appProject.layout.buildDirectory.dir( - "intermediates/stripped_native_libs/$variantName/strip${capitalizedVariantName}DebugSymbols/out/lib", - ) - it.strippedLibsDir.set(fromDirProvider) - - val stripTaskPath = ":${appProject.name}:strip${capitalizedVariantName}DebugSymbols" - val codegenTaskPath = ":${project.name}:generateCodegenSchemaFromJavaScript" - it.dependsOn(stripTaskPath, codegenTaskPath) + val jniDirs = aarLibraries.map { aarLib -> aarLib.getJniDir() } + configureProcessJniTask(it, project, appProject, projectExt, variantName, jniDirs, explodeTask) } variant.sources.jniLibs?.addGeneratedSourceDirectory( diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/utils/Extension.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/utils/Extension.kt index 4d55376a..c9830e5a 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/utils/Extension.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/utils/Extension.kt @@ -14,7 +14,9 @@ open class Extension { var appProjectName = "app" /** - * Whether to use stripped .so files. + * Whether to take the .so files from the app module's stripped or unstripped native output. It + * does not change which .so files are embedded. AGP still strips the AAR's native libs when it + * packages the library. * * Default is `true`. */ @@ -54,6 +56,17 @@ open class Extension { */ var ignoreEmbeddedLibs = listOf() + /** + * Exact .so file names, taken from the app module's native output, to embed in the AAR on top + * of the app's own libs and the embedded libraries' libs. Use it for a .so the host app cannot + * get any other way: one the app module builds or ships itself, or one from a dependency the + * published AAR does not declare. + * + * Provide in this format: + * listOf("libmmkv.so") + */ + var dynamicLibs = listOf() + /** * Whether to publish embedded native modules' third-party dependencies into the generated POM * and Gradle Module Metadata, so consuming apps resolve them instead of declaring them by hand. diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ConfigureProcessJniTaskTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ConfigureProcessJniTaskTest.kt new file mode 100644 index 00000000..c6afce0f --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ConfigureProcessJniTaskTest.kt @@ -0,0 +1,60 @@ +package com.callstack.react.brownfield.processors + +import com.callstack.react.brownfield.utils.Extension +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 + +class ConfigureProcessJniTaskTest { + @TempDir + lateinit var tempDir: File + + private fun configure(useStripped: Boolean): Pair { + 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 ext = + Extension().apply { + useStrippedSoFiles = useStripped + ignoreEmbeddedLibs = listOf("libdatadog") + dynamicLibs = listOf("libmmkv.so") + } + val explode = lib.tasks.register("explodeDevReleaseAar") + val task = lib.tasks.register("processJni", ProcessAndCopyJniLibsTask::class.java).get() + + configureProcessJniTask(task, lib, app, ext, "devRelease", listOf(File(tempDir, "jni")), explode) + return task to app.layout.buildDirectory.get().asFile + } + + @Test + fun `wires the stripped source, settings and report path`() { + val (task, appBuild) = configure(useStripped = true) + + assertEquals( + File(appBuild, "intermediates/stripped_native_libs/devRelease/stripDevReleaseDebugSymbols/out/lib"), + task.appNativeLibsDir.get().asFile, + ) + assertTrue(":app:stripDevReleaseDebugSymbols" in task.dependsOn, task.dependsOn.toString()) + assertTrue(":BrownfieldLib:generateCodegenSchemaFromJavaScript" in task.dependsOn, task.dependsOn.toString()) + assertEquals(listOf("libdatadog"), task.extraIgnoredLibs.get()) + assertEquals(listOf("libmmkv.so"), task.dynamicLibs.get()) + assertTrue( + task.skippedReportFile.get().asFile.invariantSeparatorsPath + .endsWith("BrownfieldLib/build/reports/brownfield/devRelease/skipped-so.txt"), + ) + } + + @Test + fun `wires the unstripped source`() { + val (task, appBuild) = configure(useStripped = false) + + assertEquals( + File(appBuild, "intermediates/merged_native_libs/devRelease/mergeDevReleaseNativeLibs/out/lib"), + task.appNativeLibsDir.get().asFile, + ) + assertTrue(":app:mergeDevReleaseNativeLibs" in task.dependsOn, task.dependsOn.toString()) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/JniLibsPlanTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/JniLibsPlanTest.kt new file mode 100644 index 00000000..3505751e --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/JniLibsPlanTest.kt @@ -0,0 +1,252 @@ +package com.callstack.react.brownfield.processors + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class JniLibsPlanTest { + @TempDir + lateinit var tempDir: File + + private val appDir by lazy { File(tempDir, "app") } + + private fun aarDir(name: String) = File(tempDir, "aar-$name") + + private fun so( + root: File, + abi: String, + name: String, + content: String = name, + ): File = + File(root, "$abi/$name").apply { + parentFile.mkdirs() + writeText(content) + } + + private fun plan( + aars: List = emptyList(), + app: File? = appDir, + ignored: List = IGNORE_EMBEDDED_LIBS, + dynamic: List = emptyList(), + ) = planJniLibs(aars, app, ignored, dynamic) + + @Test + fun `copies app-owned libs from the app dir`() { + val appModules = so(appDir, "arm64-v8a", "libappmodules.so") + val codegen = so(appDir, "arm64-v8a", "libreact_codegen_rnscreens.so") + + val plan = plan() + + assertEquals(appModules, plan.copies["arm64-v8a/libappmodules.so"]) + assertEquals(codegen, plan.copies["arm64-v8a/libreact_codegen_rnscreens.so"]) + } + + @Test + fun `skips app dir libs that no embedded AAR ships`() { + for (abi in listOf("arm64-v8a", "x86_64")) { + so(appDir, abi, "libQmBlur.so") + so(appDir, abi, "libandroidx.graphics.path.so") + } + + val plan = plan() + + assertTrue(plan.copies.isEmpty(), "Maven-only libs must stay out of the AAR: ${plan.copies.keys}") + } + + @Test + fun `falls back to the embedded AAR copy when the app dir lacks it`() { + val aar = aarDir("a") + val fromAar = so(aar, "arm64-v8a", "libfoo.so") + so(appDir, "arm64-v8a", "libappmodules.so") + + val plan = plan(aars = listOf(aar)) + + assertEquals(fromAar, plan.copies["arm64-v8a/libfoo.so"]) + } + + @Test + fun `drops ignored libs`() { + val aar = aarDir("a") + so(aar, "arm64-v8a", "libreactnative.so") + so(aar, "arm64-v8a", "libc++_shared.so") + so(aar, "arm64-v8a", "libdatadog-ndk.so") + so(appDir, "arm64-v8a", "libmmkv.so") + + val plan = + plan( + aars = listOf(aar), + ignored = IGNORE_EMBEDDED_LIBS + "libdatadog" + "mmkv", + dynamic = listOf("libmmkv.so"), + ) + + assertTrue(plan.copies.isEmpty(), "ignored libs were embedded: ${plan.copies.keys}") + } + + @Test + fun `keeps app-owned libs even if an ignore entry matches`() { + so(appDir, "arm64-v8a", "libappmodules.so") + + val plan = plan(ignored = listOf("libappmodules")) + + assertTrue("arm64-v8a/libappmodules.so" in plan.copies) + } + + @Test + fun `includes dynamicLibs from the app dir`() { + val mmkv = so(appDir, "arm64-v8a", "libmmkv.so") + + val plan = plan(dynamic = listOf("libmmkv.so")) + + assertEquals(mmkv, plan.copies["arm64-v8a/libmmkv.so"]) + assertTrue(plan.unmatchedDynamicLibs.isEmpty()) + } + + @Test + fun `prefers the app dir copy of a duplicate name`() { + val a = aarDir("a") + val b = aarDir("b") + so(a, "arm64-v8a", "libworklets.so", "a") + so(b, "arm64-v8a", "libworklets.so", "b") + val fromApp = so(appDir, "arm64-v8a", "libworklets.so", "app") + + val plan = plan(aars = listOf(a, b)) + + assertEquals(listOf("arm64-v8a/libworklets.so"), plan.copies.keys.toList()) + assertEquals(fromApp, plan.copies["arm64-v8a/libworklets.so"]) + } + + @Test + fun `keeps the first AAR copy of a duplicate name`() { + val a = aarDir("a") + val b = aarDir("b") + val first = so(a, "arm64-v8a", "libdup.so", "a") + so(b, "arm64-v8a", "libdup.so", "b") + + val plan = plan(aars = listOf(a, b), app = null) + + assertEquals(first, plan.copies["arm64-v8a/libdup.so"]) + } + + @Test + fun `records why each lib was skipped`() { + val aar = aarDir("a") + so(appDir, "arm64-v8a", "libQmBlur.so") + so(aar, "arm64-v8a", "libreactnative.so") + + val plan = plan(aars = listOf(aar)) + + assertEquals( + mapOf("libQmBlur.so" to SkipReason.NOT_EMBEDDED, "libreactnative.so" to SkipReason.IGNORED), + plan.skipped, + ) + } + + @Test + fun `summary lists only libs no embedded library ships`() { + val aar = aarDir("a") + so(appDir, "arm64-v8a", "libQmBlur.so") + so(appDir, "arm64-v8a", "libandroidx.graphics.path.so") + so(aar, "arm64-v8a", "libreactnative.so") + + val summary = skippedSummary(plan(aars = listOf(aar)), File("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/r/skipped-so.txt"))!! + + assertTrue(summary.startsWith("Brownfield: left 2 .so file(s) out of the AAR"), summary) + assertTrue("libQmBlur.so, libandroidx.graphics.path.so" in summary, summary) + assertTrue("your app module builds or ships it" in summary, summary) + assertTrue("reactBrownfield.dynamicLibs" in summary, summary) + assertTrue("Details: /r/skipped-so.txt" in summary, summary) + assertFalse("libreactnative.so" in summary, summary) + } + + @Test + fun `no summary when nothing is skipped as not embedded`() { + val aar = aarDir("a") + so(appDir, "arm64-v8a", "libappmodules.so") + so(aar, "arm64-v8a", "libreactnative.so") + + assertNull(skippedSummary(plan(aars = listOf(aar)), null)) + } + + @Test + fun `reports dynamicLibs entries that match nothing`() { + val plan = plan(dynamic = listOf("libnope.so", "libmmkv*.so")) + + assertEquals(setOf("libnope.so", "libmmkv*.so"), plan.unmatchedDynamicLibs) + } + + @Test + fun `only uses the ABIs the app module built`() { + val aar = aarDir("a") + so(appDir, "arm64-v8a", "libappmodules.so") + so(aar, "arm64-v8a", "libfoo.so") + so(aar, "x86_64", "libfoo.so") + + val plan = plan(aars = listOf(aar)) + + assertEquals(setOf("arm64-v8a/libappmodules.so", "arm64-v8a/libfoo.so"), plan.copies.keys) + assertEquals(setOf("x86_64"), plan.excludedAbis) + } + + @Test + fun `uses every ABI the AARs ship when the app module built none`() { + val aar = aarDir("a") + so(aar, "x86_64", "libfoo.so") + + val plan = plan(aars = listOf(aar), app = null) + + assertEquals(setOf("x86_64/libfoo.so"), plan.copies.keys) + assertTrue(plan.excludedAbis.isEmpty()) + } + + @Test + fun `warns about dynamicLibs entries that an ignore entry drops`() { + so(appDir, "arm64-v8a", "libmmkv.so") + + val plan = plan(ignored = listOf("mmkv"), dynamic = listOf("libmmkv.so")) + + assertEquals(setOf("libmmkv.so"), plan.ignoredDynamicLibs) + assertTrue(plan.unmatchedDynamicLibs.isEmpty()) + val warning = planWarnings(plan).single() + assertTrue("libmmkv.so" in warning && "ignoreEmbeddedLibs" in warning, warning) + } + + @Test + fun `warns about dynamicLibs entries that match nothing`() { + val warning = planWarnings(plan(dynamic = listOf("libnope.so"))).single() + + assertTrue("'libnope.so' matches no .so file" in warning, warning) + } + + @Test + fun `no warnings for a clean plan`() { + so(appDir, "arm64-v8a", "libappmodules.so") + + assertTrue(planWarnings(plan()).isEmpty()) + } + + @Test + fun `stripped mode reads the app's stripped output`() { + assertEquals( + AppNativeLibsSource( + "intermediates/stripped_native_libs/devRelease/stripDevReleaseDebugSymbols/out/lib", + "stripDevReleaseDebugSymbols", + ), + appNativeLibsSource("devRelease", true), + ) + } + + @Test + fun `unstripped mode reads the app's merged output`() { + assertEquals( + AppNativeLibsSource( + "intermediates/merged_native_libs/devRelease/mergeDevReleaseNativeLibs/out/lib", + "mergeDevReleaseNativeLibs", + ), + appNativeLibsSource("devRelease", false), + ) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ProcessAndCopyJniLibsTaskTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ProcessAndCopyJniLibsTaskTest.kt new file mode 100644 index 00000000..edf74e30 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/processors/ProcessAndCopyJniLibsTaskTest.kt @@ -0,0 +1,136 @@ +package com.callstack.react.brownfield.processors + +import org.gradle.api.tasks.InputDirectory +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Optional +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.assertFalse +import kotlin.test.assertTrue + +class ProcessAndCopyJniLibsTaskTest { + @TempDir + lateinit var tempDir: File + + private val out by lazy { File(tempDir, "out") } + private val report by lazy { File(tempDir, "reports/skipped-so.txt") } + + private fun so( + root: File, + abi: String, + name: String, + content: String = name, + ): File = + File(root, "$abi/$name").apply { + parentFile.mkdirs() + writeText(content) + } + + private fun runTask( + aars: List, + appDir: File, + extraIgnored: List = emptyList(), + dynamic: List = emptyList(), + ) { + val project = ProjectBuilder.builder().withProjectDir(File(tempDir, "project")).build() + val task = project.tasks.register("processJniForTest", ProcessAndCopyJniLibsTask::class.java).get() + task.aarJniDirs.setFrom(aars) + task.appNativeLibsDir.set(appDir) + task.extraIgnoredLibs.set(extraIgnored) + task.dynamicLibs.set(dynamic) + task.outputDirectory.set(out) + task.skippedReportFile.set(report) + task.execute() + } + + private fun outFiles(): Set = out.walkTopDown().filter { it.isFile }.map { it.relativeTo(out).invariantSeparatorsPath }.toSet() + + @Test + fun `copies the plan and clears stale output`() { + so(out, "arm64-v8a", "libold.so") + val app = File(tempDir, "app") + val aar = File(tempDir, "aar") + so(app, "arm64-v8a", "libappmodules.so", "app-bytes") + val aarLib = so(aar, "arm64-v8a", "libfoo.so", "aar-bytes") + + runTask(listOf(aar), app) + + assertEquals(setOf("arm64-v8a/libappmodules.so", "arm64-v8a/libfoo.so"), outFiles()) + assertEquals("app-bytes", File(out, "arm64-v8a/libappmodules.so").readText()) + assertEquals("aar-bytes", File(out, "arm64-v8a/libfoo.so").readText()) + assertTrue(aarLib.exists(), "inputs must not be modified") + } + + @Test + fun `works when the app dir does not exist`() { + val aar = File(tempDir, "aar") + so(aar, "arm64-v8a", "libfoo.so") + + runTask(listOf(aar), File(tempDir, "missing")) + + assertEquals(setOf("arm64-v8a/libfoo.so"), outFiles()) + } + + @Test + fun `writes the skipped report`() { + val app = File(tempDir, "app") + val aar = File(tempDir, "aar") + so(app, "arm64-v8a", "libQmBlur.so") + so(aar, "arm64-v8a", "libreactnative.so") + + runTask(listOf(aar), app) + + val lines = report.readLines() + val expectedFirst = skippedSummary(planJniLibs(listOf(aar), app, IGNORE_EMBEDDED_LIBS, emptyList()), null) + assertEquals(expectedFirst, lines.first()) + assertTrue("libQmBlur.so: NOT_EMBEDDED" in lines, lines.toString()) + assertTrue("libreactnative.so: IGNORED" in lines, lines.toString()) + } + + @Test + fun `writes the skipped report when nothing is skipped`() { + val app = File(tempDir, "app") + so(app, "arm64-v8a", "libappmodules.so") + + runTask(emptyList(), app) + + assertEquals(listOf("No .so files were left out."), report.readLines()) + } + + @Test + fun `applies ignoreEmbeddedLibs and dynamicLibs`() { + val app = File(tempDir, "app") + val aar = File(tempDir, "aar") + so(app, "arm64-v8a", "libmmkv.so") + so(aar, "arm64-v8a", "libdatadog-ndk.so") + so(aar, "arm64-v8a", "libfoo.so") + + runTask(listOf(aar), app, extraIgnored = listOf("libdatadog"), dynamic = listOf("libmmkv.so")) + + assertEquals(setOf("arm64-v8a/libmmkv.so", "arm64-v8a/libfoo.so"), outFiles()) + assertTrue("libdatadog-ndk.so: IGNORED" in report.readLines()) + } + + @Test + fun `app dir is not declared as an InputDirectory`() { + val getter = ProcessAndCopyJniLibsTask::class.java.getMethod("getAppNativeLibsDir") + + assertTrue(getter.isAnnotationPresent(InputFiles::class.java)) + assertTrue(getter.isAnnotationPresent(Optional::class.java)) + assertFalse(getter.isAnnotationPresent(InputDirectory::class.java)) + } + + @Test + fun `runs after the task that unpacks the embedded AARs`() { + val project = ProjectBuilder.builder().withProjectDir(File(tempDir, "project")).build() + val explode = project.tasks.register("explodeDebugAar") + val task = project.tasks.register("processJniForTest", ProcessAndCopyJniLibsTask::class.java).get() + + wireAarJniDirs(task, listOf(File(tempDir, "exploded/jni")), explode) + + assertTrue(explode.get() in task.taskDependencies.getDependencies(task)) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/utils/ExtensionTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/utils/ExtensionTest.kt index b9e5f81b..9bcbb672 100644 --- a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/utils/ExtensionTest.kt +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/utils/ExtensionTest.kt @@ -8,4 +8,9 @@ class ExtensionTest { fun `experimentalIncludeTransitiveDependencies defaults to true`() { assertTrue(Extension().experimentalIncludeTransitiveDependencies) } + + @Test + fun `dynamicLibs defaults to an empty list`() { + assertTrue(Extension().dynamicLibs.isEmpty()) + } }