diff --git a/.changeset/bump-bgp-alpha09.md b/.changeset/bump-bgp-alpha09.md new file mode 100644 index 000000000..80efc2549 --- /dev/null +++ b/.changeset/bump-bgp-alpha09.md @@ -0,0 +1,5 @@ +--- +'@callstack/react-native-brownfield': patch +--- + +Bump the Brownfield Gradle Plugin version injected by the Expo config plugin to `2.0.0-alpha09`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 229ba5dcd..bc0c9acc7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,6 +143,7 @@ jobs: needs.filter.outputs.expo56 == 'true' || needs.filter.outputs.androidapp == 'true' || needs.filter.outputs.packages == 'true' || + needs.filter.outputs.gradle-plugins == 'true' || needs.filter.outputs.ci == 'true' ) && (needs.build-lint.result == 'success' || needs.build-lint.result == 'skipped') @@ -172,6 +173,7 @@ jobs: needs.filter.outputs.expo56 == 'true' || needs.filter.outputs.androidapp == 'true' || needs.filter.outputs.packages == 'true' || + needs.filter.outputs.gradle-plugins == 'true' || needs.filter.outputs.ci == 'true' ) && (needs.build-lint.result == 'success' || needs.build-lint.result == 'skipped') && @@ -202,6 +204,7 @@ jobs: needs.filter.outputs.expo57 == 'true' || needs.filter.outputs.androidapp == 'true' || needs.filter.outputs.packages == 'true' || + needs.filter.outputs.gradle-plugins == 'true' || needs.filter.outputs.ci == 'true' ) && (needs.build-lint.result == 'success' || needs.build-lint.result == 'skipped') @@ -231,6 +234,7 @@ jobs: needs.filter.outputs.expo57 == 'true' || needs.filter.outputs.androidapp == 'true' || needs.filter.outputs.packages == 'true' || + needs.filter.outputs.gradle-plugins == 'true' || needs.filter.outputs.ci == 'true' ) && (needs.build-lint.result == 'success' || needs.build-lint.result == 'skipped') && diff --git a/.github/workflows/gradle-plugin-lint.yml b/.github/workflows/gradle-plugin-lint.yml index 81298b6e2..f0d2de0c1 100644 --- a/.github/workflows/gradle-plugin-lint.yml +++ b/.github/workflows/gradle-plugin-lint.yml @@ -29,3 +29,7 @@ jobs: - name: Run KtLint working-directory: gradle-plugins/react/brownfield run: ./gradlew ktlintCheck --no-daemon --stacktrace + + - name: Run Unit Tests + working-directory: gradle-plugins/react/brownfield + run: ./gradlew test --no-daemon --stacktrace diff --git a/.gitignore b/.gitignore index a05d1915f..873cd0ec5 100644 --- a/.gitignore +++ b/.gitignore @@ -91,4 +91,8 @@ packages/react-native-brownfield/ios/swiftpm/.build/ # skillgym .skillgym-results/ +# internal process artifacts (should never be part of the PR diff) +.superpowers/ +docs/superpowers/ + .cursor diff --git a/apps/RNApp/android/BrownfieldLib/build.gradle.kts b/apps/RNApp/android/BrownfieldLib/build.gradle.kts index e876cc24f..543147908 100644 --- a/apps/RNApp/android/BrownfieldLib/build.gradle.kts +++ b/apps/RNApp/android/BrownfieldLib/build.gradle.kts @@ -1,6 +1,3 @@ -import groovy.json.JsonOutput -import groovy.json.JsonSlurper - plugins { id("com.android.library") id("org.jetbrains.kotlin.android") @@ -18,22 +15,6 @@ publishing { afterEvaluate { from(components.getByName("default")) } - - pom { - withXml { - /** - * As a result of `from(components.getByName("default"))` all of the project - * dependencies are added to `pom.xml` file. We do not need the react-native - * third party dependencies to be a part of it as we embed those dependencies. - */ - val dependenciesNode = - (asNode().get("dependencies") as groovy.util.NodeList).first() as groovy.util.Node - dependenciesNode.children() - .filterIsInstance() - .filter { (it.get("groupId") as groovy.util.NodeList).text() == rootProject.name } - .forEach { dependenciesNode.remove(it) } - } - } } } @@ -42,29 +23,6 @@ publishing { } } -val moduleBuildDir: Directory = layout.buildDirectory.get() - -/** - * As a result of `from(components.getByName("default"))` all of the project - * dependencies are added to `module.json` file. We do not need the react-native - * third party dependencies to be a part of it as we embed those dependencies. - */ -tasks.register("removeDependenciesFromModuleFile") { - doLast { - file("$moduleBuildDir/publications/mavenAar/module.json").run { - val json = inputStream().use { JsonSlurper().parse(it) as Map } - (json["variants"] as? List>)?.forEach { variant -> - (variant["dependencies"] as? MutableList>)?.removeAll { it["group"] == rootProject.name } - } - writer().use { it.write(JsonOutput.prettyPrint(JsonOutput.toJson(json))) } - } - } -} - -tasks.named("generateMetadataFileForMavenAarPublication") { - finalizedBy("removeDependenciesFromModuleFile") -} - react { autolinkLibrariesWithApp() } @@ -128,9 +86,8 @@ android { } dependencies { - implementation("androidx.core:core-ktx:1.17.0") - implementation("androidx.appcompat:appcompat:1.7.1") - implementation("com.google.android.material:material:1.13.0") + // react-native-screens' androidx deps are deliberately not declared here — the plugin + // discovers them. Hand-declaring would mask a broken discoverer. testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.3.0") androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") diff --git a/apps/RNApp/android/build.gradle b/apps/RNApp/android/build.gradle index dba7507fa..cd1bbe0ee 100644 --- a/apps/RNApp/android/build.gradle +++ b/apps/RNApp/android/build.gradle @@ -16,7 +16,7 @@ buildscript { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") - classpath("com.callstack.react:brownfield-gradle-plugin:2.0.0-alpha08-SNAPSHOT") + classpath("com.callstack.react:brownfield-gradle-plugin:2.0.0-alpha09-SNAPSHOT") } } diff --git a/apps/scripts/prepare-android-build-gradle-for-ci.ts b/apps/scripts/prepare-android-build-gradle-for-ci.ts index a990fc8ee..02cfd6000 100644 --- a/apps/scripts/prepare-android-build-gradle-for-ci.ts +++ b/apps/scripts/prepare-android-build-gradle-for-ci.ts @@ -9,7 +9,7 @@ if (!projectDirName) { const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const SNAPSHOT_VERSION = '2.0.0-alpha08-SNAPSHOT'; +const SNAPSHOT_VERSION = '2.0.0-alpha09-SNAPSHOT'; const targetPath = path.resolve( __dirname, '..', diff --git a/docs/docs/docs/getting-started/android.mdx b/docs/docs/docs/getting-started/android.mdx index 0f55091c1..818fb2a64 100644 --- a/docs/docs/docs/getting-started/android.mdx +++ b/docs/docs/docs/getting-started/android.mdx @@ -312,7 +312,11 @@ publishing { mavenLocal() } } +``` + +Skip this task-registration block entirely — `experimentalIncludeTransitiveDependencies` (described below) is enabled by default and already does this for you. +```kotlin val moduleBuildDir: Directory = layout.buildDirectory.get() tasks.register("removeDependenciesFromModuleFile") { @@ -332,6 +336,18 @@ tasks.named("generateMetadataFileForMavenAarPublication") { } ``` +> **Transitive dependencies:** by default, the plugin discovers your embedded native modules' own third-party dependencies (e.g. AndroidX libraries pulled in by `react-native-screens`) and publishes them into this AAR's POM/Gradle Module Metadata, so the app consuming this AAR resolves them automatically via Maven — no manual step needed. +> +> If you'd rather hand-declare these yourself instead (e.g. while this is still experimental), set `experimentalIncludeTransitiveDependencies = false` in this module's `reactBrownfield { }` block and use the task-registration block above: +> +> ```kotlin +> reactBrownfield { +> experimentalIncludeTransitiveDependencies = false +> } +> ``` +> +> If you are upgrading an existing app that already has the hand-written `tasks.register("removeDependenciesFromModuleFile")` block above, you can leave it in place — the plugin's own task is named differently (`brownfieldRemoveDependenciesFromModuleFile`) and the two do not conflict. It is redundant once `experimentalIncludeTransitiveDependencies` is enabled (the plugin performs the same removal), so you can delete it whenever convenient. + ## 7. Create a Brownfield Configuration Create `brownfield.config.json` in your project root: diff --git a/docs/docs/docs/guides/troubleshooting.mdx b/docs/docs/docs/guides/troubleshooting.mdx index 46ce0bd2b..d3f89064f 100644 --- a/docs/docs/docs/guides/troubleshooting.mdx +++ b/docs/docs/docs/guides/troubleshooting.mdx @@ -12,11 +12,13 @@ The brownfield Gradle plugin adds both directories to the source sets, potential ## [Android] Transitive dependencies not being auto resolved -Installed third-party packages like `react-native-screens` or others may rely on transitive dependencies in their `build.gradle` file. These dependencies are not auto resolved by `brownfield-gradle-plugin`. This is an intended behavior in bare React Native apps. +Installed third-party packages like `react-native-screens` or others may rely on transitive dependencies in their `build.gradle` file. For bare React Native apps, `brownfield-gradle-plugin` auto resolves these by default via the (experimental) `experimentalIncludeTransitiveDependencies` option — see [Configure Maven Publishing](/docs/getting-started/android#6-configure-maven-publishing) for details. -For Expo apps, this should work out of the box. +For Expo apps, this works out of the box unconditionally. -To make it work with bare React Native Apps, you have two options: +Upgrading an existing app requires no changes on your side — in particular, you do not need to remove the hand-written `tasks.register("removeDependenciesFromModuleFile")` block if you have one, since the plugin's own task is named differently and the two do not conflict. Be aware of two behaviour changes once this is enabled: dependencies your embedded modules need will start appearing in the published POM, and a version you pinned yourself may be **raised** (never lowered) if an embedded module requires a higher one. + +If you've set `experimentalIncludeTransitiveDependencies = false` (e.g. to opt out while this is still experimental), use one of the options below instead. #### Option 1: diff --git a/gradle-plugins/react/brownfield/build.gradle.kts b/gradle-plugins/react/brownfield/build.gradle.kts index ad2a04a7f..b73354d78 100644 --- a/gradle-plugins/react/brownfield/build.gradle.kts +++ b/gradle-plugins/react/brownfield/build.gradle.kts @@ -108,6 +108,13 @@ dependencies { implementation(libs.common) implementation(libs.asm.commons) implementation(libs.versioncompare) + testImplementation(libs.junit.jupiter) + testImplementation(gradleTestKit()) + testImplementation(kotlin("test")) +} + +tasks.test { + useJUnitPlatform() } tasks.named("detekt").configure { diff --git a/gradle-plugins/react/brownfield/gradle.properties b/gradle-plugins/react/brownfield/gradle.properties index abcabe8c5..769b32a16 100644 --- a/gradle-plugins/react/brownfield/gradle.properties +++ b/gradle-plugins/react/brownfield/gradle.properties @@ -1,6 +1,6 @@ PROJECT_ID=com.callstack.react.brownfield ARTIFACT_ID=brownfield-gradle-plugin -VERSION=2.0.0-alpha08 +VERSION=2.0.0-alpha09 GROUP=com.callstack.react IMPLEMENTATION_CLASS=com.callstack.react.brownfield.plugin.RNBrownfieldPlugin diff --git a/gradle-plugins/react/brownfield/gradle/libs.versions.toml b/gradle-plugins/react/brownfield/gradle/libs.versions.toml index b1b599711..74ecb0541 100644 --- a/gradle-plugins/react/brownfield/gradle/libs.versions.toml +++ b/gradle-plugins/react/brownfield/gradle/libs.versions.toml @@ -6,6 +6,7 @@ agp = "8.5.2" common = "31.2.2" # do not bump it for now, as it throws an error for incompatible AGP used asm-commons = "9.7" versioncompare = "1.5.0" +junit = "5.11.4" [plugins] kotlinJvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlinJvm" } @@ -17,3 +18,4 @@ agp = { module = "com.android.tools.build:gradle", name = "agp", version.ref = " common = { module = "com.android.tools:common", version.ref = "common" } asm-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm-commons" } versioncompare = { module = "io.github.g00fy2:versioncompare", version.ref = "versioncompare" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscoverer.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscoverer.kt new file mode 100644 index 000000000..24a5e0ea7 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscoverer.kt @@ -0,0 +1,96 @@ +package com.callstack.react.brownfield.artifacts + +import com.callstack.react.brownfield.shared.Logging +import com.callstack.react.brownfield.shared.TRANSITIVE_DEPENDENCY_CONFIG_NAMES +import com.callstack.react.brownfield.shared.UnresolvedArtifactInfo +import com.callstack.react.brownfield.shared.VersionMediatingDependencySet +import com.callstack.react.brownfield.shared.collectPublishableGradleDependencies +import com.callstack.react.brownfield.shared.isPublishableCoordinate +import org.gradle.api.Project +import org.gradle.api.artifacts.Dependency + +/** + * Result of [RncTransitiveDependencyDiscoverer.discover]. + * + * @param dependencies The mediated set of third-party dependencies to inject. + * @param supersededCoordinates Coordinates the consumer declares itself that an embedded module + * also needs. The caller must drop their pre-existing POM/module.json entries: [dependencies] + * already carries the mediated (never-lower) version, so keeping both duplicates or shadows it. + */ +data class RncTransitiveDependencyDiscoveryResult( + val dependencies: VersionMediatingDependencySet, + val supersededCoordinates: Set>, +) + +/** + * Discovers third-party dependencies of the native modules embedded into the fat AAR, for + * publication into its POM/module metadata. The RNC-CLI counterpart to + * `ExpoPublishingHelper.appendExpoTransitiveDependenciesFromGradle`. + */ +class RncTransitiveDependencyDiscoverer(private val project: Project) { + fun discover(artifacts: List): RncTransitiveDependencyDiscoveryResult { + val discovered = VersionMediatingDependencySet() + val supersededCoordinates = mutableSetOf>() + + artifacts + .filter { it.isExpoPublishDependency != true } + .forEach { artifact -> discoverFromArtifact(artifact, discovered, supersededCoordinates) } + + return RncTransitiveDependencyDiscoveryResult(discovered, supersededCoordinates) + } + + private fun discoverFromArtifact( + artifact: UnresolvedArtifactInfo, + discovered: VersionMediatingDependencySet, + supersededCoordinates: MutableSet>, + ) { + val moduleProject = project.rootProject.findProject(":${artifact.moduleName}") + if (moduleProject == null) { + Logging.log( + "WARNING: Could not discover transitive dependencies for embedded module " + + "'${artifact.moduleName}' - no Gradle project found at " + + "':${artifact.moduleName}' in the root project", + ) + return + } + + collectPublishableGradleDependencies(moduleProject).forEach { moduleDependency -> + val consumerDeclaration = consumerDeclaredDependency(moduleDependency.groupId, moduleDependency.artifactId) + + if (consumerDeclaration != null) { + // Supersede on the declaration existing, not on it having a version: a versionless + // one (BOM/platform) still leaves a stale entry that must be replaced, not doubled. + supersededCoordinates.add(moduleDependency.groupId to moduleDependency.artifactId) + + // Module-side versions are already validated upstream; this is the consumer-side + // equivalent, keeping a dynamic version from winning mediation and being published. + val consumerVersioned = moduleDependency.copy(version = consumerDeclaration.version) + if (isPublishableCoordinate(consumerVersioned)) { + discovered.add(consumerVersioned) + } + } + + discovered.add(moduleDependency) + } + } + + /** + * The consumer's own declaration of this coordinate, or null if it doesn't declare it. Returns + * the [Dependency], not its version, so "declared without a version" stays distinguishable from + * "not declared" — collapsing the two leaks duplicate POM entries. + * + * Note this narrows a dynamic declaration: consumer `appcompat:1.+` against module `1.0.0` + * publishes `1.0.0`, possibly lower than `1.+` would have resolved to. Intended — a published + * `1.+` is broken for downstream consumers. + */ + private fun consumerDeclaredDependency( + groupId: String, + artifactId: String, + ): Dependency? { + return TRANSITIVE_DEPENDENCY_CONFIG_NAMES.firstNotNullOfOrNull { configName -> + project.configurations.findByName(configName)?.dependencies?.firstOrNull { + it.group == groupId && it.name == artifactId + } + } + } +} diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelper.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelper.kt index 72c4288ba..1c2b19efe 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelper.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelper.kt @@ -1,20 +1,15 @@ package com.callstack.react.brownfield.expo import com.android.utils.forEach -import com.callstack.react.brownfield.expo.utils.DependencyInfo import com.callstack.react.brownfield.expo.utils.ExpoGradleProjectProjection import com.callstack.react.brownfield.expo.utils.LocalMavenUtils -import com.callstack.react.brownfield.expo.utils.VersionMediatingDependencySet import com.callstack.react.brownfield.expo.utils.asExpoGradleProjectProjection import com.callstack.react.brownfield.shared.Constants +import com.callstack.react.brownfield.shared.DependencyInfo import com.callstack.react.brownfield.shared.Logging -import groovy.json.JsonOutput -import groovy.json.JsonSlurper -import groovy.util.NodeList +import com.callstack.react.brownfield.shared.VersionMediatingDependencySet +import com.callstack.react.brownfield.shared.collectPublishableGradleDependencies import org.gradle.api.Project -import org.gradle.api.publish.PublishingExtension -import org.gradle.api.publish.maven.MavenPublication -import org.gradle.api.publish.tasks.GenerateModuleMetadata import org.w3c.dom.Node import java.io.File import javax.xml.parsers.DocumentBuilderFactory @@ -29,6 +24,11 @@ fun Node.getChildNodeByName(nodeName: String): Node? { } open class ExpoPublishingHelper(val brownfieldAppProject: Project) { + /** + * Discovers *which* Expo projects are publishable, not their transitive dependencies: this runs + * during `apply()`, when those projects may not have configured their own dependencies yet. + * [discoverAllExpoTransitiveDependencies] handles that later. + */ fun configure(): List { val discoverableExpoProjects = getDiscoverableExpoProjects() @@ -39,29 +39,10 @@ open class ExpoPublishingHelper(val brownfieldAppProject: Project) { ) { it.name }, ) - val expoTransitiveDependencies = - discoverAllExpoTransitiveDependencies( - expoProjects = discoverableExpoProjects, - ) - - Logging.log( - "Collected a total of ${expoTransitiveDependencies.size} unique Expo transitive " + - "dependencies for brownfield app project publishing", - ) - expoTransitiveDependencies.forEach { - Logging.log( - "(*) dependency ${it.groupId}:${it.artifactId}:${it.version} (scope: ${it.scope}, " + - "${if (it.optional) "optional" else "required"})", - ) - } - - reconfigurePOM(expoTransitiveDependencies) - reconfigureGradleModuleJSON(expoTransitiveDependencies) - return discoverableExpoProjects } - protected fun shouldExcludeDependency( + internal fun shouldExcludeDependency( groupId: String, artifactId: String, ): Boolean { @@ -78,174 +59,6 @@ open class ExpoPublishingHelper(val brownfieldAppProject: Project) { return (isRootProjectArtifact || isExpoArtifact) } - /** - * Modifies the generated Gradle Module Metadata file to inject Expo transitive dependencies. - * @param discoveredExpoTransitiveDependencies Set of DependencyInfo - * representing Expo transitive dependencies to add. - */ - @Suppress("LongMethod") - protected fun reconfigureGradleModuleJSON(discoveredExpoTransitiveDependencies: VersionMediatingDependencySet) { - val removeDependenciesFromModuleFileTask = - brownfieldAppProject.tasks.register("removeDependenciesFromModuleFile") - removeDependenciesFromModuleFileTask.configure { task -> - task.doLast { - val moduleBuildDir = brownfieldAppProject.layout.buildDirectory.get() - - File("$moduleBuildDir/publications/mavenAar/module.json").run { - val json = inputStream().use { JsonSlurper().parse(it) as Map<*, *> } - - discoveredExpoTransitiveDependencies.forEach { dependencyToAdd -> - @Suppress("UNCHECKED_CAST") - (json["variants"] as? List>)?.forEach { variant -> - Logging.log( - "Injecting dependency to Gradle module JSON for variant " + - "'${variant["name"]}': ${dependencyToAdd.groupId}:" + - "${dependencyToAdd.artifactId}:${dependencyToAdd.version}", - ) - - (variant["dependencies"] as? MutableList>)?.add( - mutableMapOf( - "group" to dependencyToAdd.groupId, - "module" to dependencyToAdd.artifactId, - ).apply { - dependencyToAdd.version?.let { version -> - put( - "version", - mapOf( - "requires" to version, - ), - ) - } - }, - ) - } - } - - @Suppress("UNCHECKED_CAST") - (json["variants"] as? List>)?.forEach { variant -> - (variant["dependencies"] as? MutableList>)?.removeAll { - val group = it["group"] as String - val module = it["module"] as String - - val shouldBeExcluded = - shouldExcludeDependency( - groupId = group, - artifactId = module, - ) - - if (shouldBeExcluded) { - Logging.log( - "Removing excluded dependency from Gradle module JSON: $group:$module", - ) - } - - shouldBeExcluded - } - - writer().use { - it.write( - JsonOutput.prettyPrint( - JsonOutput.toJson( - json, - ), - ), - ) - } - } - } - } - } - - brownfieldAppProject.tasks.withType(GenerateModuleMetadata::class.java) - .configureEach { - it.finalizedBy(removeDependenciesFromModuleFileTask.get()) - } - } - - /** - * Modifies the generated Maven POM file to inject Expo transitive dependencies. - * @param discoveredExpoTransitiveDependencies Set of DependencyInfo - * representing Expo transitive dependencies to add. - */ - @Suppress("LongMethod") - protected fun reconfigurePOM(discoveredExpoTransitiveDependencies: VersionMediatingDependencySet) { - brownfieldAppProject.pluginManager.withPlugin("maven-publish") { - brownfieldAppProject.extensions.configure(PublishingExtension::class.java) { publishing -> - publishing.publications.withType(MavenPublication::class.java) - .configureEach { pub -> - Logging.log( - "Configuring POM for publication '${pub.name}' to include Expo transitive dependencies", - ) - - pub.pom.withXml { - val root = it.asNode() - - // below: obtains a view of the node(s) - // inside the POM XML; in practice, there should be only one such node - val dependenciesNodeList = - root.get("dependencies") as NodeList - val dependenciesNode = - dependenciesNodeList.first() as groovy.util.Node - - // below: inject the discovered Expo transitive dependencies - // into the POM's node - discoveredExpoTransitiveDependencies.forEach { dependencyToAdd -> - Logging.log( - "Injecting dependency to POM: ${dependencyToAdd.groupId}:" + - "${dependencyToAdd.artifactId}:${dependencyToAdd.version}", - ) - - val childTags = - mutableMapOf( - "groupId" to dependencyToAdd.groupId, - "artifactId" to dependencyToAdd.artifactId, - "scope" to dependencyToAdd.scope, - "optional" to dependencyToAdd.optional.toString(), - ) - - if (dependencyToAdd.version?.isNotBlank() == true) { - childTags["version"] = dependencyToAdd.version - } - - dependenciesNode.appendNode("dependency").let { newDepNode -> - childTags.forEach { (tagName, tagValue) -> - newDepNode.appendNode(tagName, tagValue) - } - } - } - - // below: filter out dependencies that should be excluded - dependenciesNode.children() - .filterIsInstance() - .filter { dependency -> - val groupId = - (dependency["groupId"] as NodeList).text() - val artifactId = - (dependency["artifactId"] as NodeList).text() - - val shouldBeExcluded = - shouldExcludeDependency( - groupId = groupId, - artifactId = artifactId, - ) - - if (shouldBeExcluded) { - Logging.log( - "Removing excluded dependency from POM: $groupId:$artifactId", - ) - } - - shouldBeExcluded - } - .forEach { dependency -> - dependenciesNode.remove(dependency) - } - } - } - } - } - } - fun discoverAllExpoTransitiveDependencies(expoProjects: Iterable): VersionMediatingDependencySet { var discoveredExpoTransitiveDependencies = VersionMediatingDependencySet() expoProjects.forEach { expoProj -> @@ -368,24 +181,7 @@ open class ExpoPublishingHelper(val brownfieldAppProject: Project) { pkgProject: Project, dependencies: VersionMediatingDependencySet, ) { - /** - * Not accounting for variant specific configurations as Expo packages are not - * using it. Should we face any issues/needs to account for it, we can do it here. - */ - listOf("implementation", "api", "runtime").forEach { - val configuration = pkgProject.configurations.findByName(it) - configuration?.dependencies?.forEach { dep -> - if (dep.group != null) { - dependencies.add( - DependencyInfo.fromGradleDep( - groupId = dep.group!!, - artifactId = dep.name, - version = dep.version, - ), - ) - } - } - } + dependencies.addAll(collectPublishableGradleDependencies(pkgProject)) } /** diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPublishingInfo.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPublishingInfo.kt new file mode 100644 index 000000000..10ef2ae2e --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPublishingInfo.kt @@ -0,0 +1,7 @@ +package com.callstack.react.brownfield.expo.utils + +data class BrownfieldPublishingInfo( + val groupId: String, + val artifactId: String, + val version: String, +) 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 a408f586c..72b2c1f9d 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 @@ -3,6 +3,7 @@ package com.callstack.react.brownfield.plugin import com.android.build.api.variant.LibraryAndroidComponentsExtension import com.android.build.api.variant.LibraryVariant import com.callstack.react.brownfield.artifacts.ArtifactsResolver +import com.callstack.react.brownfield.artifacts.RncTransitiveDependencyDiscoverer import com.callstack.react.brownfield.expo.ExpoPublishingHelper import com.callstack.react.brownfield.expo.utils.ExpoGradleProjectProjection import com.callstack.react.brownfield.processors.AssetTaskProcessor @@ -15,9 +16,13 @@ import com.callstack.react.brownfield.processors.VariantHelper import com.callstack.react.brownfield.processors.VariantPackagesProperty import com.callstack.react.brownfield.processors.VariantTaskProvider import com.callstack.react.brownfield.shared.BaseProject +import com.callstack.react.brownfield.shared.Constants import com.callstack.react.brownfield.shared.Constants.PROJECT_ID import com.callstack.react.brownfield.shared.Logging +import com.callstack.react.brownfield.shared.PublishingMetadataInjector import com.callstack.react.brownfield.shared.UnresolvedArtifactInfo +import com.callstack.react.brownfield.shared.VersionMediatingDependencySet +import com.callstack.react.brownfield.shared.dropHardExcludedDependencies import com.callstack.react.brownfield.utils.AndroidArchiveLibrary import com.callstack.react.brownfield.utils.DirectoryManager import com.callstack.react.brownfield.utils.Extension @@ -54,8 +59,9 @@ class RNBrownfieldPlugin : Plugin { } var expoProjects = listOf() + var expoPublishingHelper: ExpoPublishingHelper? = null if (this.isExpoProject) { - val expoPublishingHelper = ExpoPublishingHelper(brownfieldAppProject = project) + expoPublishingHelper = ExpoPublishingHelper(brownfieldAppProject = project) expoProjects = expoPublishingHelper.configure() } @@ -65,6 +71,18 @@ class RNBrownfieldPlugin : Plugin { val artifactsResolver = ArtifactsResolver(project, isExpoProject) val artifacts = artifactsResolver.processDefaultDependencies(expoProjects) + // Registered eagerly: Gradle disallows registering tasks from afterEvaluate. Only the + // dependency set supplied below has to wait. + val injector = PublishingMetadataInjector(project) + + // whenReady, not afterEvaluate: afterEvaluate guarantees only that *this* project is + // configured, not the embedded module projects we read dependencies from — theirs were + // empirically still empty at that point. whenReady fires once the whole task graph is + // resolved (so every embedded module is configured) but before any task runs. + project.gradle.taskGraph.whenReady { + configureTransitiveDependencyInjection(project, injector, expoPublishingHelper, expoProjects, artifacts) + } + val variantTaskProvider = VariantTaskProvider(project) val androidComponents = project.extensions.getByType(LibraryAndroidComponentsExtension::class.java) @@ -77,6 +95,79 @@ class RNBrownfieldPlugin : Plugin { const val EXPO_PROJECT_LOCATOR = ":expo" } + @Suppress("LongMethod") + private fun configureTransitiveDependencyInjection( + project: Project, + injector: PublishingMetadataInjector, + expoPublishingHelper: ExpoPublishingHelper?, + expoProjects: List, + artifacts: List, + ) { + val transitiveDeps = VersionMediatingDependencySet() + var rncSupersededCoordinates: Set> = emptySet() + + if (isExpoProject && expoPublishingHelper != null) { + val expoTransitiveDeps = expoPublishingHelper.discoverAllExpoTransitiveDependencies(expoProjects) + Logging.log("Merged ${expoTransitiveDeps.size} transitive dependencies discovered from Expo") + expoTransitiveDeps.forEach { + Logging.log( + "(*) dependency ${it.groupId}:${it.artifactId}:${it.version} (scope: ${it.scope}, " + + "${if (it.optional) "optional" else "required"})", + ) + } + transitiveDeps.addAll(expoTransitiveDeps) + } + // Never on Expo: the path above already covers every embedded module there, and the RNC + // discoverer doesn't filter by the Expo blacklist, so running both leaks Expo coordinates. + if (!isExpoProject && extension.experimentalIncludeTransitiveDependencies) { + val rncDiscovery = RncTransitiveDependencyDiscoverer(project).discover(artifacts) + Logging.log( + "Merged ${rncDiscovery.dependencies.size} transitive dependencies discovered by the RNC discoverer", + ) + transitiveDeps.addAll(rncDiscovery.dependencies) + rncSupersededCoordinates = rncDiscovery.supersededCoordinates + } + + if (isExpoProject || extension.experimentalIncludeTransitiveDependencies) { + // Coordinates that must never be published: they're embedded in the AAR, not + // resolvable from Maven. Distinct from "superseded" coordinates, which ARE re-injected + // (replacing a stale entry) and so must not be dropped here. + val hardExcludePredicate: (String, String) -> Boolean = { groupId, artifactId -> + (expoPublishingHelper?.shouldExcludeDependency(groupId, artifactId) ?: (groupId == project.rootProject.name)) || + artifacts.any { it.moduleGroup == groupId && it.moduleName == artifactId } + } + dropHardExcludedDependencies(transitiveDeps, hardExcludePredicate) + + Logging.log( + "Total of ${transitiveDeps.size} unique transitive dependencies merged for POM/module.json injection", + ) + + val removalPredicate: (String, String) -> Boolean = { groupId, artifactId -> + hardExcludePredicate(groupId, artifactId) || rncSupersededCoordinates.contains(groupId to artifactId) + } + + injector.configure(transitiveDeps, removalPredicate) + Logging.log("PublishingMetadataInjector ran: injected merged transitive dependencies into POM and Gradle Module Metadata") + + // Informational only — throwing would recreate the upgrade break that the namespaced + // task name exists to prevent. `names` avoids realizing the task from whenReady. + if (project.tasks.names.contains(Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME)) { + Logging.log( + "NOTE: this project still registers a hand-written " + + "'${Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME}' task. The plugin now performs " + + "that removal itself (plus transitive-dependency injection) via " + + "'${Constants.MODULE_METADATA_POST_PROCESS_TASK_NAME}'. The hand-written task is " + + "redundant and can be deleted; leaving it in place is harmless.", + ) + } + } else { + Logging.log( + "PublishingMetadataInjector skipped: project is not an Expo project and " + + "experimentalIncludeTransitiveDependencies is disabled", + ) + } + } + private fun initializers() { RClassTransformer.project = project Logging.project = project diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/Constants.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/Constants.kt index d6a5537f5..e10a330f7 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/Constants.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/Constants.kt @@ -1,6 +1,5 @@ package com.callstack.react.brownfield.shared -import com.callstack.react.brownfield.expo.utils.DependencyInfo import com.callstack.react.brownfield.utils.StringMatcher /** @@ -40,6 +39,18 @@ object Constants { const val INTERMEDIATES_TEMP_DIR = PLUGIN_NAME + /** + * Plugin-owned task that post-processes generated Gradle Module Metadata. + * + * Never rename to the bare [LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME]: the plugin registers + * during `apply()`, before the consumer's script body, so claiming that name breaks every + * consumer still following the setup docs with "a task with that name already exists". + */ + const val MODULE_METADATA_POST_PROCESS_TASK_NAME = "brownfieldRemoveDependenciesFromModuleFile" + + /** The name the setup docs tell consumers to register themselves; must stay free for them. */ + const val LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME = "removeDependenciesFromModuleFile" + val BROWNFIELD_EXPO_TRANSITIVE_DEPS_WHITELISTED_MODULES_FOR_DISCOVERY = setOf("expo-modules-core", "expo-constants", "expo", "expo-updates") val BROWNFIELD_EXPO_TRANSITIVE_DEPS_ARTIFACTS_BLACKLIST = diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPrimitives.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyInfo.kt similarity index 72% rename from gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPrimitives.kt rename to gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyInfo.kt index e051a820f..09a0eab55 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/BrownfieldPrimitives.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyInfo.kt @@ -1,10 +1,4 @@ -package com.callstack.react.brownfield.expo.utils - -data class BrownfieldPublishingInfo( - val groupId: String, - val artifactId: String, - val version: String, -) +package com.callstack.react.brownfield.shared data class DependencyInfo( val groupId: String, @@ -18,12 +12,13 @@ data class DependencyInfo( groupId: String, artifactId: String, version: String?, + scope: String = "compile", ): DependencyInfo { return DependencyInfo( groupId = groupId, artifactId = artifactId, version = version, - scope = "compile", + scope = scope, optional = false, ) } diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyPublishability.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyPublishability.kt new file mode 100644 index 000000000..c7768cb53 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/DependencyPublishability.kt @@ -0,0 +1,22 @@ +package com.callstack.react.brownfield.shared + +/** Matches Maven/Gradle version-range syntax, e.g. `[1.0,2.0)`, `(,2.0]`, `[1.0,)`. */ +private val VERSION_RANGE_REGEX = Regex("^[\\[(].*,.*[\\])]$") + +/** Reserved Gradle/Maven dynamic-version keywords that resolve to whatever is newest at build time. */ +private val DYNAMIC_VERSION_KEYWORDS = setOf("latest.release", "latest.integration", "latest", "release") + +/** + * Whether [dependency] is safe to publish as-is. Rejects dynamic versions (`+`, `latest.*`, ranges) + * and blank ones: the former resolve non-reproducibly for consumers, the latter emit a + * `` with no version at all. + */ +fun isPublishableCoordinate(dependency: DependencyInfo): Boolean { + val version = dependency.version + if (version.isNullOrBlank()) return false + val trimmed = version.trim() + if (trimmed.contains("+")) return false + if (trimmed.lowercase() in DYNAMIC_VERSION_KEYWORDS) return false + if (VERSION_RANGE_REGEX.matches(trimmed)) return false + return true +} diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/GradleDependencyCollector.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/GradleDependencyCollector.kt new file mode 100644 index 000000000..15ec80095 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/GradleDependencyCollector.kt @@ -0,0 +1,44 @@ +package com.callstack.react.brownfield.shared + +import org.gradle.api.Project +import org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency + +/** + * Configurations inspected when discovering a project's direct external dependencies. + * + * Not flavor-aware — `releaseImplementation` and friends are missed. Fine for Expo packages, which + * don't use them; extend if an RNC-CLI native module turns out to. + */ +val TRANSITIVE_DEPENDENCY_CONFIG_NAMES = listOf("implementation", "api", "runtimeOnly") + +/** Maven scope per configuration; `runtimeOnly` maps to `runtime` to keep it off the compile classpath. */ +private val CONFIG_NAME_TO_SCOPE = + mapOf( + "implementation" to "compile", + "api" to "compile", + "runtimeOnly" to "runtime", + ) + +/** + * [project]'s direct external (non-project) dependencies on [TRANSITIVE_DEPENDENCY_CONFIG_NAMES], + * minus anything [isPublishableCoordinate] rejects. Shared by the Expo fallback and RNC paths so + * both get the same guarantees. + */ +fun collectPublishableGradleDependencies(project: Project): List { + val result = mutableListOf() + + TRANSITIVE_DEPENDENCY_CONFIG_NAMES.forEach { configName -> + val configuration = project.configurations.findByName(configName) ?: return@forEach + val scope = CONFIG_NAME_TO_SCOPE.getValue(configName) + + configuration.dependencies.forEach { dependency -> + if (dependency is DefaultProjectDependency) return@forEach + val group = dependency.group ?: return@forEach + + val info = DependencyInfo.fromGradleDep(group, dependency.name, dependency.version, scope) + if (isPublishableCoordinate(info)) result.add(info) + } + } + + return result +} diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjector.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjector.kt new file mode 100644 index 000000000..41dd7556a --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjector.kt @@ -0,0 +1,181 @@ +package com.callstack.react.brownfield.shared + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper +import groovy.util.Node +import groovy.util.NodeList +import org.gradle.api.Project +import org.gradle.api.publish.PublishingExtension +import org.gradle.api.publish.maven.MavenPublication +import org.gradle.api.publish.tasks.GenerateModuleMetadata + +/** + * Removes every `` matching [shouldExclude] from [dependenciesNode], then appends one + * per entry in [dependencies]. + * + * Removal must run before appending: [shouldExclude] matches on coordinate alone, so afterwards it + * couldn't tell a stale superseded entry from the one just appended for it, and would drop both. + */ +internal fun mutatePomDependenciesNode( + dependenciesNode: Node, + dependencies: VersionMediatingDependencySet, + shouldExclude: (groupId: String, artifactId: String) -> Boolean, +) { + dependenciesNode.children() + .filterIsInstance() + .filter { dependency -> + val groupId = (dependency["groupId"] as NodeList).text() + val artifactId = (dependency["artifactId"] as NodeList).text() + shouldExclude(groupId, artifactId) + } + .forEach { dependency -> + dependenciesNode.remove(dependency) + } + + dependencies.forEach { dependencyToAdd -> + val childTags = + mutableMapOf( + "groupId" to dependencyToAdd.groupId, + "artifactId" to dependencyToAdd.artifactId, + "scope" to dependencyToAdd.scope, + "optional" to dependencyToAdd.optional.toString(), + ) + + if (dependencyToAdd.version?.isNotBlank() == true) { + childTags["version"] = dependencyToAdd.version + } + + dependenciesNode.appendNode("dependency").let { newDepNode -> + childTags.forEach { (tagName, tagValue) -> + newDepNode.appendNode(tagName, tagValue) + } + } + } +} + +/** + * The POM's `` element, created if absent — a publication with no dependencies has + * none, and `first()` throws on it. Extracted so tests exercise this code rather than + * reimplementing the fallback and passing regardless of what production does. + */ +internal fun resolveOrCreateDependenciesNode(root: Node): Node = + (root.get("dependencies") as NodeList).firstOrNull() as? Node + ?: root.appendNode("dependencies") + +/** + * The `module.json` equivalent of [mutatePomDependenciesNode], applied to every variant's + * `dependencies` list. Same removal-before-append requirement, for the same reason. + */ +internal fun mutateModuleJsonVariants( + json: Map<*, *>, + dependencies: VersionMediatingDependencySet, + shouldExclude: (groupId: String, artifactId: String) -> Boolean, +) { + @Suppress("UNCHECKED_CAST") + (json["variants"] as? List>)?.forEach { variant -> + (variant["dependencies"] as? MutableList>)?.removeAll { + val group = it["group"] as String + val module = it["module"] as String + shouldExclude(group, module) + } + } + + dependencies.forEach { dependencyToAdd -> + @Suppress("UNCHECKED_CAST") + (json["variants"] as? List>)?.forEach { variant -> + // Known gap: every dependency lands in every variant, so runtime-scoped ones are + // compile-visible to Gradle consumers. A fix must key on provenance, NOT on + // `scope`, which means different things per path: on the Expo path "runtime" is what + // Gradle emits for `implementation` (73 of 84 deps across the upstream Expo POMs), on + // the RNC path it means `runtimeOnly`. Filtering on it would strip react-android and + // appcompat from Expo consumers. Needs a `fromRuntimeOnlyConfiguration` flag on + // DependencyInfo, and its own PR. + (variant["dependencies"] as? MutableList>)?.add( + mutableMapOf( + "group" to dependencyToAdd.groupId, + "module" to dependencyToAdd.artifactId, + ).apply { + dependencyToAdd.version?.let { version -> + put("version", mapOf("requires" to version)) + } + }, + ) + } + } +} + +/** + * Injects transitive dependencies into the generated Maven POM and Gradle Module Metadata for + * every `MavenPublication` on [project], removing any existing entry the exclusion predicate + * matches. Used identically by the Expo and RNC-CLI paths. + * + * Hooks are registered eagerly on construction, since Gradle disallows registering tasks from + * `afterEvaluate`. The dependency set isn't known until then, so [configure] supplies it later; + * until it's called, injection is disabled and the hooks are no-ops. + */ +class PublishingMetadataInjector(private val project: Project) { + private var dependencies = VersionMediatingDependencySet() + private var shouldExclude: (groupId: String, artifactId: String) -> Boolean = { _, _ -> false } + private var enabled = false + + init { + registerModuleJsonInjectors() + registerPomInjector() + } + + /** Supplies the dependencies to inject and enables injection on the hooks registered in [init]. */ + fun configure( + dependencies: VersionMediatingDependencySet, + shouldExclude: (groupId: String, artifactId: String) -> Boolean, + ) { + this.dependencies = dependencies + this.shouldExclude = shouldExclude + this.enabled = true + } + + private fun registerModuleJsonInjectors() { + // One task, not one per publication registered from a GenerateModuleMetadata + // configureEach — that crashes with "DefaultTaskContainer#register(String) ... cannot be + // executed in the current context". Walking each task's outputFile at execution time also + // avoids hardcoding a publication name. Name is namespaced: see Constants. + val removeDependenciesFromModuleFileTask = + project.tasks.register(Constants.MODULE_METADATA_POST_PROCESS_TASK_NAME) + removeDependenciesFromModuleFileTask.configure { task -> + task.onlyIf { enabled } + task.doLast { + project.tasks.withType(GenerateModuleMetadata::class.java).forEach { metadataTask -> + val moduleFile = metadataTask.outputFile.get().asFile + if (!moduleFile.exists()) return@forEach + + val json = moduleFile.inputStream().use { JsonSlurper().parse(it) as Map<*, *> } + mutateModuleJsonVariants(json, dependencies, shouldExclude) + moduleFile.writer().use { + it.write(JsonOutput.prettyPrint(JsonOutput.toJson(json))) + } + } + } + } + + // Finalizing with an already-registered task is safe here, unlike registering one. + project.tasks.withType(GenerateModuleMetadata::class.java).configureEach { metadataTask -> + metadataTask.finalizedBy(removeDependenciesFromModuleFileTask) + } + } + + private fun registerPomInjector() { + project.pluginManager.withPlugin("maven-publish") { + project.extensions.configure(PublishingExtension::class.java) { publishing -> + publishing.publications.withType(MavenPublication::class.java) + .configureEach { pub -> + pub.pom.withXml { + if (!enabled) return@withXml + + val root = it.asNode() + val dependenciesNode = resolveOrCreateDependenciesNode(root) + mutatePomDependenciesNode(dependenciesNode, dependencies, shouldExclude) + } + } + } + } + } +} diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFiltering.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFiltering.kt new file mode 100644 index 000000000..e62642d8c --- /dev/null +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFiltering.kt @@ -0,0 +1,17 @@ +package com.callstack.react.brownfield.shared + +/** + * Drops coordinates matching [hardExcludePredicate] — ones that are embedded in the AAR and so + * would never resolve from Maven. A discovery path can surface these without knowing it: the RNC + * discoverer has no Expo awareness, so an embedded module depending on an Expo module coordinate + * would otherwise be published as an ordinary dependency. + * + * [hardExcludePredicate] must never include superseded coordinates — those are meant to be + * re-injected with the mediated version, and dropping them here removes them entirely. + */ +internal fun dropHardExcludedDependencies( + transitiveDeps: VersionMediatingDependencySet, + hardExcludePredicate: (groupId: String, artifactId: String) -> Boolean, +): VersionMediatingDependencySet { + return transitiveDeps.filter { !hardExcludePredicate(it.groupId, it.artifactId) } +} diff --git a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/VersionMediatingDependencySet.kt b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySet.kt similarity index 98% rename from gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/VersionMediatingDependencySet.kt rename to gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySet.kt index b7dc2bc7e..c86777844 100644 --- a/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/expo/utils/VersionMediatingDependencySet.kt +++ b/gradle-plugins/react/brownfield/src/main/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySet.kt @@ -1,4 +1,4 @@ -package com.callstack.react.brownfield.expo.utils +package com.callstack.react.brownfield.shared import io.github.g00fy2.versioncompare.Version 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 5bebbfac3..bb9c79da2 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 @@ -53,4 +53,15 @@ open class Extension { * listOf("libdatadog-ndk.so") */ var ignoreEmbeddedLibs = 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. + * + * Experimental; behavior may still change. Applies to non-Expo (RNC CLI) projects only — Expo + * gets this unconditionally. Set to `false` to hand-declare them instead. + * + * Default is `true`. + */ + var experimentalIncludeTransitiveDependencies = true } diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscovererTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscovererTest.kt new file mode 100644 index 000000000..6ace77c18 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/artifacts/RncTransitiveDependencyDiscovererTest.kt @@ -0,0 +1,171 @@ +package com.callstack.react.brownfield.artifacts + +import com.callstack.react.brownfield.shared.DependencyInfo +import com.callstack.react.brownfield.shared.UnresolvedArtifactInfo +import org.gradle.testfixtures.ProjectBuilder +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class RncTransitiveDependencyDiscovererTest { + private fun defaultArtifacts(root: org.gradle.api.Project) = + listOf( + UnresolvedArtifactInfo( + moduleGroup = root.name, + moduleName = "react-native-fake-module", + moduleVersion = "unspecified", + file = null, + isExpoPublishDependency = false, + ), + ) + + @Test + fun `a dynamic consumer-declared version never becomes a mediation candidate`() { + // Module-side versions are validated by collectPublishableGradleDependencies; the + // consumer side must be validated too, or `1.+` can win mediation and be published. + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.dependencies.add("implementation", "androidx.appcompat:appcompat:1.0.0") + + consumer.configurations.create("implementation") + consumer.dependencies.add("implementation", "androidx.appcompat:appcompat:1.+") + + val result = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)) + + val appcompat = result.dependencies.first { it.groupId == "androidx.appcompat" } + assertEquals("1.0.0", appcompat.version, "the dynamic consumer version must not win mediation") + assertFalse(result.dependencies.any { it.version == "1.+" }, "'1.+' must never reach the published set") + } + + @Test + fun `a versionless consumer declaration still supersedes, so the coordinate is not duplicated`() { + // Declared via BOM/platform, so `.version` is null. A version-only lookup returns null + // here, never marks the coordinate superseded, and leaves two entries for it in the POM. + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.dependencies.add("implementation", "androidx.appcompat:appcompat:1.7.1") + + consumer.configurations.create("implementation") + consumer.dependencies.add("implementation", "androidx.appcompat:appcompat") + + val result = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)) + + assertTrue( + result.supersededCoordinates.contains("androidx.appcompat" to "appcompat"), + "a declared-but-versionless coordinate must still be superseded", + ) + assertEquals("1.7.1", result.dependencies.first { it.groupId == "androidx.appcompat" }.version) + } + + @Test + fun `discovers a module's direct external dependencies, skipping project deps and non-publishable coordinates`() { + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + val siblingProject = ProjectBuilder.builder().withParent(root).withName("some-other-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.configurations.create("api") + embeddedModule.configurations.create("runtimeOnly") + + embeddedModule.dependencies.add("implementation", "androidx.appcompat:appcompat:1.7.1") + embeddedModule.dependencies.add("implementation", "com.facebook.react:react-native:+") + embeddedModule.dependencies.add("runtimeOnly", "androidx.annotation:annotation:1.9.1") + embeddedModule.dependencies.add( + "implementation", + embeddedModule.dependencies.project(mapOf("path" to siblingProject.path)), + ) + + consumer.configurations.create("api") + + val result = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)) + val discovered = result.dependencies + + assertEquals(2, discovered.size) + assertTrue( + discovered.contains( + DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false), + ), + ) + assertTrue( + discovered.contains( + DependencyInfo("androidx.annotation", "annotation", "1.9.1", "runtime", false), + ), + ) + assertFalse(discovered.contains(DependencyInfo("com.facebook.react", "react-native", "+", "compile", false))) + assertFalse(discovered.contains(DependencyInfo(root.name, "some-other-module", "unspecified", "compile", false))) + assertTrue(result.supersededCoordinates.isEmpty()) + } + + @Test + fun `publishes a runtimeOnly dependency under Maven runtime scope, not compile`() { + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.configurations.create("api") + embeddedModule.configurations.create("runtimeOnly") + embeddedModule.dependencies.add("runtimeOnly", "androidx.annotation:annotation:1.9.1") + + val discovered = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)).dependencies + + val annotationDep = discovered.first { it.groupId == "androidx.annotation" } + assertEquals("runtime", annotationDep.scope) + } + + @Test + fun `a module's higher version requirement wins over, and supersedes, the consumer's own lower declaration`() { + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.configurations.create("api") + embeddedModule.configurations.create("runtimeOnly") + embeddedModule.dependencies.add("implementation", "androidx.appcompat:appcompat:1.7.1") + + consumer.configurations.create("api") + consumer.dependencies.add("api", "androidx.appcompat:appcompat:1.6.0") + + val result = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)) + + val appcompatDep = result.dependencies.first { it.groupId == "androidx.appcompat" } + assertEquals("1.7.1", appcompatDep.version, "the module's higher requirement must win mediation") + assertTrue( + result.supersededCoordinates.contains("androidx.appcompat" to "appcompat"), + "the consumer's stale lower-version entry must be marked for replacement", + ) + } + + @Test + fun `does not regress or supersede when the consumer's own version already satisfies the module`() { + val root = ProjectBuilder.builder().build() + val consumer = ProjectBuilder.builder().withParent(root).withName("BrownfieldLib").build() + val embeddedModule = ProjectBuilder.builder().withParent(root).withName("react-native-fake-module").build() + + embeddedModule.configurations.create("implementation") + embeddedModule.configurations.create("api") + embeddedModule.configurations.create("runtimeOnly") + embeddedModule.dependencies.add("implementation", "androidx.appcompat:appcompat:1.6.0") + + consumer.configurations.create("api") + consumer.dependencies.add("api", "androidx.appcompat:appcompat:1.7.1") + + val result = RncTransitiveDependencyDiscoverer(consumer).discover(defaultArtifacts(root)) + + val appcompatDep = result.dependencies.first { it.groupId == "androidx.appcompat" } + assertEquals("1.7.1", appcompatDep.version, "the consumer's already-higher version must be preserved, not downgraded") + assertTrue( + result.supersededCoordinates.contains("androidx.appcompat" to "appcompat"), + "still marked superseded so the injector re-declares it at the mediated (unchanged) version instead of duplicating it", + ) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelperGradleFallbackTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelperGradleFallbackTest.kt new file mode 100644 index 000000000..9308c1d61 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/expo/ExpoPublishingHelperGradleFallbackTest.kt @@ -0,0 +1,47 @@ +package com.callstack.react.brownfield.expo + +import com.callstack.react.brownfield.shared.VersionMediatingDependencySet +import org.gradle.api.Project +import org.gradle.testfixtures.ProjectBuilder +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class ExpoPublishingHelperGradleFallbackTest { + @Test + fun `Gradle-fallback discovery picks up runtimeOnly dependencies`() { + val root = ProjectBuilder.builder().build() + val expoPkgProject = ProjectBuilder.builder().withParent(root).withName("expo-fake-module").build() + + expoPkgProject.configurations.create("implementation") + expoPkgProject.configurations.create("api") + expoPkgProject.configurations.create("runtimeOnly") + expoPkgProject.dependencies.add("runtimeOnly", "androidx.annotation:annotation:1.9.1") + + val helper = + object : ExpoPublishingHelper(brownfieldAppProject = root) { + fun exposedAppend( + pkgProject: Project, + deps: VersionMediatingDependencySet, + ) { + appendExpoTransitiveDependenciesFromGradle(pkgProject, deps) + } + } + + val discovered = VersionMediatingDependencySet() + helper.exposedAppend(expoPkgProject, discovered) + + // Coordinate-only check: VersionMediatingDependencySet keys on groupId/artifactId, so + // passing a scope here would be inert and would read as contradicting the scope + // assertion below. + assertTrue( + discovered.any { it.groupId == "androidx.annotation" && it.artifactId == "annotation" }, + "expected the runtimeOnly dependency to be discovered via the Gradle fallback path", + ) + assertEquals( + "runtime", + discovered.first { it.groupId == "androidx.annotation" }.scope, + "runtimeOnly dependencies should be published under Maven's runtime scope, not compile", + ) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/plugin/LegacyConsumerConfigurationTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/plugin/LegacyConsumerConfigurationTest.kt new file mode 100644 index 000000000..b5330a048 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/plugin/LegacyConsumerConfigurationTest.kt @@ -0,0 +1,110 @@ +package com.callstack.react.brownfield.plugin + +import com.callstack.react.brownfield.shared.Constants +import org.gradle.testkit.runner.GradleRunner +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File +import kotlin.test.assertFalse + +/** + * Guards the pre-migration consumer shape no in-repo app has any more: one that still hand-registers + * `removeDependenciesFromModuleFile` as the setup docs instruct. If the plugin ever claims that name + * again, configuration fails outright for every consumer who hasn't migrated. + * + * Skipped without an Android SDK, since the plugin requires `com.android.library`. + */ +class LegacyConsumerConfigurationTest { + @Test + fun `a project still registering the documented legacy task configures successfully`( + @TempDir projectDir: File, + ) { + val androidSdk = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") + assumeTrue( + androidSdk != null && File(androidSdk).isDirectory, + "no Android SDK available (ANDROID_HOME/ANDROID_SDK_ROOT); skipping AGP-dependent test", + ) + + writeLegacyConsumerFixture(projectDir, androidSdk!!) + + val result = + GradleRunner.create() + .withProjectDir(projectDir) + .withPluginClasspath() + .withArguments("tasks", "--stacktrace") + .forwardOutput() + .build() + + // build() already failed above on any unrelated fixture breakage; this narrows a failure + // here to the duplicate-task-name case specifically. + assertFalse( + result.output.contains("as a task with that name already exists"), + "build output reports a duplicate task name; the plugin most likely claimed " + + "'${Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME}', which the setup docs " + + "reserve for consumers", + ) + } + + private fun writeLegacyConsumerFixture( + projectDir: File, + androidSdk: String, + ) { + File(projectDir, "settings.gradle.kts").writeText( + """ + dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } + } + rootProject.name = "legacy-consumer" + include(":app") + include(":brownfieldlib") + """.trimIndent(), + ) + File(projectDir, "local.properties").writeText("sdk.dir=$androidSdk\n") + // ArtifactsResolver looks for an `app` project; an empty stub is enough, this test is about + // the task container, not discovery. + File(projectDir, "app").mkdirs() + File(projectDir, "app/build.gradle.kts").writeText("") + + // The `tasks.register("removeDependenciesFromModuleFile")` block below is verbatim from + // the published setup docs. Do not "modernize" it — its whole purpose is to reproduce + // what a not-yet-migrated consumer actually has in their build script. + File(projectDir, "brownfieldlib").mkdirs() + File(projectDir, "brownfieldlib/build.gradle.kts").writeText( + """ + import groovy.json.JsonOutput + import groovy.json.JsonSlurper + + plugins { + id("com.android.library") + id("com.callstack.react.brownfield") + `maven-publish` + } + + android { + namespace = "com.example.legacyconsumer" + compileSdk = 34 + } + + val moduleBuildDir: Directory = layout.buildDirectory.get() + + tasks.register("removeDependenciesFromModuleFile") { + doLast { + file("${'$'}moduleBuildDir/publications/mavenAar/module.json").run { + val json = inputStream().use { JsonSlurper().parse(it) as Map } + (json["variants"] as? List>)?.forEach { variant -> + (variant["dependencies"] as? MutableList>)?.removeAll { + it["group"] == rootProject.name + } + } + writer().use { it.write(JsonOutput.prettyPrint(JsonOutput.toJson(json))) } + } + } + } + """.trimIndent(), + ) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/DependencyPublishabilityTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/DependencyPublishabilityTest.kt new file mode 100644 index 000000000..17b31cb59 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/DependencyPublishabilityTest.kt @@ -0,0 +1,67 @@ +package com.callstack.react.brownfield.shared + +import org.junit.jupiter.api.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class DependencyPublishabilityTest { + @Test + fun `rejects a fully dynamic version`() { + val dep = DependencyInfo("com.facebook.react", "react-native", "+", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects a partially dynamic version`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "1.+", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects a null version`() { + val dep = DependencyInfo("com.facebook.react", "react-android", null, "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects a blank version`() { + val dep = DependencyInfo("com.facebook.react", "react-android", " ", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `accepts a normal pinned version`() { + val dep = DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false) + assertTrue(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects latest_release`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "latest.release", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects latest_integration`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "latest.integration", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects a closed Maven version range`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "[1.0,2.0]", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects a half-open Maven version range`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "[1.0,2.0)", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } + + @Test + fun `rejects an unbounded Maven version range`() { + val dep = DependencyInfo("androidx.core", "core-ktx", "[1.0,)", "compile", false) + assertFalse(isPublishableCoordinate(dep)) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjectorTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjectorTest.kt new file mode 100644 index 000000000..a31db038a --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/PublishingMetadataInjectorTest.kt @@ -0,0 +1,222 @@ +package com.callstack.react.brownfield.shared + +import groovy.util.NodeList +import groovy.xml.XmlParser +import org.gradle.testfixtures.ProjectBuilder +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class PublishingMetadataInjectorTaskRegistrationTest { + @Test + fun `does not claim the task name the setup docs tell consumers to register`() { + val project = ProjectBuilder.builder().build() + + PublishingMetadataInjector(project) + + assertNull( + project.tasks.findByName(Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME), + "the plugin must leave this name free: the published setup docs tell every bare-RN " + + "consumer to register it themselves, and the plugin applies before their script body", + ) + assertNotNull( + project.tasks.findByName(Constants.MODULE_METADATA_POST_PROCESS_TASK_NAME), + ) + } + + @Test + fun `a not-yet-migrated consumer can still register the legacy task after the plugin has run`() { + // The upgrade path at the task-container level: plugin registers during apply(), then the + // consumer's script body registers the task the docs told them to. Must not throw. + val project = ProjectBuilder.builder().build() + + PublishingMetadataInjector(project) + project.tasks.register(Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME) + + assertNotNull(project.tasks.findByName(Constants.LEGACY_CONSUMER_MODULE_METADATA_TASK_NAME)) + assertNotNull(project.tasks.findByName(Constants.MODULE_METADATA_POST_PROCESS_TASK_NAME)) + } +} + +class MutatePomDependenciesNodeTest { + private fun dependenciesNodeFrom(xml: String): groovy.util.Node { + val root = XmlParser().parseText(xml) + return (root.get("dependencies") as NodeList).first() as groovy.util.Node + } + + private fun versionsFor( + dependenciesNode: groovy.util.Node, + groupId: String, + artifactId: String, + ): List { + return dependenciesNode.children() + .filterIsInstance() + .filter { + (it["groupId"] as NodeList).text() == groupId && (it["artifactId"] as NodeList).text() == artifactId + } + .map { (it["version"] as NodeList).text() } + } + + @Test + fun `appends new dependencies with no pre-existing entries`() { + val dependenciesNode = dependenciesNodeFrom("") + val toInject = VersionMediatingDependencySet() + toInject.add(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false)) + + mutatePomDependenciesNode(dependenciesNode, toInject) { _, _ -> false } + + assertEquals(listOf("1.17.0"), versionsFor(dependenciesNode, "androidx.core", "core-ktx")) + } + + @Test + fun `injects into a POM that has no dependencies element at all`() { + // Must call resolveOrCreateDependenciesNode — inlining the fallback here would make this + // pass even with the production path reverted to first(). + val root = XmlParser().parseText("") + val toInject = VersionMediatingDependencySet() + toInject.add(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false)) + + val dependenciesNode = resolveOrCreateDependenciesNode(root) + mutatePomDependenciesNode(dependenciesNode, toInject) { _, _ -> false } + + assertEquals(listOf("1.17.0"), versionsFor(dependenciesNode, "androidx.core", "core-ktx")) + } + + @Test + fun `reuses the existing dependencies element instead of appending a second one`() { + val root = + XmlParser().parseText( + """ + + + + androidx.core + core-ktx + 1.17.0 + + + + """.trimIndent(), + ) + + val dependenciesNode = resolveOrCreateDependenciesNode(root) + + assertEquals( + 1, + (root.get("dependencies") as NodeList).size, + "a POM that already has must not gain a second one", + ) + assertEquals(listOf("1.17.0"), versionsFor(dependenciesNode, "androidx.core", "core-ktx")) + } + + @Test + fun `removes an unrelated excluded entry that is not being re-injected`() { + val dependenciesNode = + dependenciesNodeFrom( + """ + + + + com.rnapp + brownfieldlib + unspecified + + + + """.trimIndent(), + ) + + mutatePomDependenciesNode(dependenciesNode, VersionMediatingDependencySet()) { groupId, _ -> + groupId == "com.rnapp" + } + + assertTrue(versionsFor(dependenciesNode, "com.rnapp", "brownfieldlib").isEmpty()) + } + + @Test + fun `a superseded stale entry is replaced by the mediated version, not left duplicated or missing`() { + // Consumer hand-declares 1.6.0, embedded module needs 1.7.1, so the coordinate is + // superseded and shouldExclude matches it. The mediated 1.7.1 must survive exactly once. + val dependenciesNode = + dependenciesNodeFrom( + """ + + + + androidx.appcompat + appcompat + 1.6.0 + runtime + + + + """.trimIndent(), + ) + val mediated = VersionMediatingDependencySet() + mediated.add(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false)) + + mutatePomDependenciesNode(dependenciesNode, mediated) { groupId, artifactId -> + groupId == "androidx.appcompat" && artifactId == "appcompat" + } + + assertEquals(listOf("1.7.1"), versionsFor(dependenciesNode, "androidx.appcompat", "appcompat")) + } +} + +class MutateModuleJsonVariantsTest { + private fun jsonWithVariant(dependencies: MutableList>): MutableMap { + return mutableMapOf( + "variants" to + mutableListOf( + mutableMapOf( + "name" to "runtimeElements", + "dependencies" to dependencies, + ), + ), + ) + } + + @Suppress("UNCHECKED_CAST") + private fun dependenciesOf(json: Map<*, *>): List> { + val variants = json["variants"] as List> + return variants.first()["dependencies"] as List> + } + + @Test + fun `appends new dependencies with no pre-existing entries`() { + val json = jsonWithVariant(mutableListOf()) + val toInject = VersionMediatingDependencySet() + toInject.add(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false)) + + mutateModuleJsonVariants(json, toInject) { _, _ -> false } + + val deps = dependenciesOf(json) + assertEquals(1, deps.size) + assertEquals("androidx.core", deps.first()["group"]) + assertEquals("core-ktx", deps.first()["module"]) + } + + @Test + fun `a superseded stale entry is replaced by the mediated version, not left duplicated or missing`() { + val json = + jsonWithVariant( + mutableListOf( + mutableMapOf("group" to "androidx.appcompat", "module" to "appcompat"), + ), + ) + val mediated = VersionMediatingDependencySet() + mediated.add(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false)) + + mutateModuleJsonVariants(json, mediated) { group, module -> + group == "androidx.appcompat" && module == "appcompat" + } + + val deps = dependenciesOf(json) + assertEquals(1, deps.size, "expected exactly one entry, not zero (deleted) or two (duplicated)") + @Suppress("UNCHECKED_CAST") + val version = (deps.first()["version"] as? Map)?.get("requires") + assertEquals("1.7.1", version) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFilteringTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFilteringTest.kt new file mode 100644 index 000000000..7f643ca7c --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/TransitiveDependencyFilteringTest.kt @@ -0,0 +1,37 @@ +package com.callstack.react.brownfield.shared + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TransitiveDependencyFilteringTest { + @Test + fun `drops a hard-excluded coordinate the RNC discoverer found, even though it has no Expo awareness`() { + // The RNC discoverer has no Expo blacklist, so an embedded module depending on an Expo + // coordinate would otherwise be published as a Maven dependency that resolves nowhere. + val transitiveDeps = VersionMediatingDependencySet() + transitiveDeps.add(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false)) + transitiveDeps.add(DependencyInfo("host.exp.exponent", "expo.modules.device", "56.0.4", "compile", false)) + + val hardExcludePredicate: (String, String) -> Boolean = { groupId, _ -> groupId == "host.exp.exponent" } + dropHardExcludedDependencies(transitiveDeps, hardExcludePredicate) + + assertTrue(transitiveDeps.contains(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false))) + assertFalse(transitiveDeps.any { it.groupId == "host.exp.exponent" }) + assertEquals(1, transitiveDeps.size) + } + + @Test + fun `does not drop a superseded coordinate that is meant to still be injected`() { + // hardExcludePredicate must never include the supersede check, or a mediated + // replacement for a consumer's stale hand-declared dependency would be dropped too. + val transitiveDeps = VersionMediatingDependencySet() + transitiveDeps.add(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false)) + + dropHardExcludedDependencies(transitiveDeps) { _, _ -> false } + + assertTrue(transitiveDeps.contains(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false))) + assertEquals(1, transitiveDeps.size) + } +} diff --git a/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySetTest.kt b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySetTest.kt new file mode 100644 index 000000000..927f8dc50 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/shared/VersionMediatingDependencySetTest.kt @@ -0,0 +1,42 @@ +package com.callstack.react.brownfield.shared + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class VersionMediatingDependencySetTest { + @Test + fun `keeps the higher version when the same coordinate is added twice`() { + val set = VersionMediatingDependencySet() + + set.add(DependencyInfo("androidx.appcompat", "appcompat", "1.6.0", "compile", false)) + set.add(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false)) + + assertEquals(1, set.size) + assertTrue(set.contains(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false))) + } + + @Test + fun `does not downgrade when a lower version is added second`() { + val set = VersionMediatingDependencySet() + + set.add(DependencyInfo("androidx.appcompat", "appcompat", "1.7.1", "compile", false)) + set.add(DependencyInfo("androidx.appcompat", "appcompat", "1.6.0", "compile", false)) + + val kept = set.first { it.groupId == "androidx.appcompat" } + assertEquals("1.7.1", kept.version) + } + + @Test + fun `removeAll removes matching entries and returns them`() { + val set = VersionMediatingDependencySet() + set.add(DependencyInfo("host.exp.exponent", "expo", "1.0.0", "compile", false)) + set.add(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false)) + + val removed = set.removeAll { it.groupId == "host.exp.exponent" } + + assertEquals(1, removed.size) + assertEquals(1, set.size) + assertTrue(set.contains(DependencyInfo("androidx.core", "core-ktx", "1.17.0", "compile", false))) + } +} 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 new file mode 100644 index 000000000..b9e5f81b2 --- /dev/null +++ b/gradle-plugins/react/brownfield/src/test/kotlin/com/callstack/react/brownfield/utils/ExtensionTest.kt @@ -0,0 +1,11 @@ +package com.callstack.react.brownfield.utils + +import org.junit.jupiter.api.Test +import kotlin.test.assertTrue + +class ExtensionTest { + @Test + fun `experimentalIncludeTransitiveDependencies defaults to true`() { + assertTrue(Extension().experimentalIncludeTransitiveDependencies) + } +} diff --git a/packages/react-native-brownfield/src/expo-config-plugin/android/__tests__/gradleHelpers.test.ts b/packages/react-native-brownfield/src/expo-config-plugin/android/__tests__/gradleHelpers.test.ts index 013bad14f..5fde6d54b 100644 --- a/packages/react-native-brownfield/src/expo-config-plugin/android/__tests__/gradleHelpers.test.ts +++ b/packages/react-native-brownfield/src/expo-config-plugin/android/__tests__/gradleHelpers.test.ts @@ -16,7 +16,7 @@ describe('gradleHelpers', () => { }`; expect(modifyRootBuildGradle(contents)).toContain( - 'classpath("com.callstack.react:brownfield-gradle-plugin:2.0.0-alpha08")' + 'classpath("com.callstack.react:brownfield-gradle-plugin:2.0.0-alpha09")' ); }); diff --git a/packages/react-native-brownfield/src/expo-config-plugin/android/utils/constants.ts b/packages/react-native-brownfield/src/expo-config-plugin/android/utils/constants.ts index f7aee9d01..51d012df9 100644 --- a/packages/react-native-brownfield/src/expo-config-plugin/android/utils/constants.ts +++ b/packages/react-native-brownfield/src/expo-config-plugin/android/utils/constants.ts @@ -1,2 +1,2 @@ -export const BROWNFIELD_PLUGIN_VERSION = '2.0.0-alpha08'; +export const BROWNFIELD_PLUGIN_VERSION = '2.0.0-alpha09'; export const brownfieldGradlePluginDependency = `classpath("com.callstack.react:brownfield-gradle-plugin:${BROWNFIELD_PLUGIN_VERSION}")`; diff --git a/scripts/__tests__/generate-brownfield-gradle-plugin-release-notes.test.ts b/scripts/__tests__/generate-brownfield-gradle-plugin-release-notes.test.ts index 78e98096c..87cf1d62b 100644 --- a/scripts/__tests__/generate-brownfield-gradle-plugin-release-notes.test.ts +++ b/scripts/__tests__/generate-brownfield-gradle-plugin-release-notes.test.ts @@ -25,14 +25,14 @@ test('supports prerelease versions when finding the previous plugin tag', () => const previousTag = findPreviousPluginTag( [ 'brownfield-gradle-plugin/v2.0.0-alpha01', - 'brownfield-gradle-plugin/v2.0.0-alpha08', + 'brownfield-gradle-plugin/v2.0.0-alpha09', 'brownfield-gradle-plugin/v2.0.0-beta01', 'brownfield-gradle-plugin/v2.0.0', ], '2.0.0-beta01' ); - assert.equal(previousTag, 'brownfield-gradle-plugin/v2.0.0-alpha08'); + assert.equal(previousTag, 'brownfield-gradle-plugin/v2.0.0-alpha09'); }); test('treats a stable release as newer than its prereleases', () => {