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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/bgp-exclude-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@callstack/react-native-brownfield': minor
'@callstack/brownfield-cli': minor
---

feat: the published POM and `module.json` now follow the brownfield module's Gradle exclude rules (`configurations.all { exclude(...) }`). Before, the plugin re-added an excluded dependency when it injected the embedded libraries' dependencies, so the host app still resolved it. The excludes are also written onto every dependency the plugin injects, so the excluded library can't arrive through one of them. On Expo, list them in `android.excludeDependencies` (as `group:module` or `group`), which the config plugin writes into the generated module.
2 changes: 1 addition & 1 deletion apps/RNApp/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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-alpha13-SNAPSHOT")
classpath("com.callstack.react:brownfield-gradle-plugin:2.0.0-alpha14-SNAPSHOT")
}
}

Expand Down
2 changes: 1 addition & 1 deletion apps/scripts/prepare-android-build-gradle-for-ci.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ if (!projectDirName) {

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const SNAPSHOT_VERSION = '2.0.0-alpha13-SNAPSHOT';
const SNAPSHOT_VERSION = '2.0.0-alpha14-SNAPSHOT';
// Accepts a repo-relative app dir (e.g. "ExpoApp58") or an absolute path (e.g.
// the scaffold-smoke app created outside the repo).
const projectDir = path.isAbsolute(projectDirName)
Expand Down
1 change: 1 addition & 0 deletions docs/docs/docs/api-reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ All file-based platform options mirror CLI flags, but they use camelCase propert
| `android.expo.minifyEnabled` | `boolean` | Controls `minifyEnabled` for the generated Android library build. Disabled by default. |
| `android.expo.extraProguardRules` | `string[]`| Additional Proguard rules appended to the generated `proguard-rules.pro`. |
| `android.expo.useLocalMaven` | `boolean` | Load the Brownfield Gradle plugin published to local maven instead of using from remote. Disabled by default. |
| `android.expo.excludeDependencies` | `string[]` | Dependencies to keep out of the published AAR's POM and `module.json`, as `group:module` or `group` for a whole group. Written into the generated module as Gradle `exclude` rules. |

Example:

Expand Down
21 changes: 21 additions & 0 deletions gradle-plugins/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,27 @@ dependencies {
}
```

<hr/>

The published POM and `module.json` follow the brownfield module's Gradle exclude rules. Put the exclude in the brownfield module's `build.gradle.kts`, for example when two libraries ship the same classes under different artifacts:

```kts
configurations.all {
exclude(group = "com.caverock", module = "androidsvg")
}
```

The excluded dependency is left out of the published files, and is written as an exclusion on every published dependency, so the host app doesn't get it through one of them either. Use this instead of a custom task that edits the published files: the plugin rewrites them after Gradle generates them, so an earlier edit would be lost.

Only `exclude` rules on the `implementation`, `api`, `runtimeOnly` and `embed` configurations count. These are not read:

- excludes in `:app`: they describe the standalone React Native app, which may leave out things the host app needs
- excludes on a variant's configuration (`debugRuntimeClasspath`): every variant publishes the same list
- excludes on a single dependency (`implementation("x") { exclude(...) }`): they only apply under that dependency
- `resolutionStrategy` substitutions and capability rules

On Expo, prebuild regenerates the brownfield module, so list the dependencies in `brownfield.config.json` under `android.expo.excludeDependencies` (or under `android.excludeDependencies` in the plugin's options in `app.json`), as `group:module` or `group`. Prebuild writes them into the module as the `configurations.all` block above.

<hr/>
<br/>

Expand Down
2 changes: 1 addition & 1 deletion gradle-plugins/react/brownfield/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
PROJECT_ID=com.callstack.react.brownfield
ARTIFACT_ID=brownfield-gradle-plugin
VERSION=2.0.0-alpha13
VERSION=2.0.0-alpha14
GROUP=com.callstack.react
IMPLEMENTATION_CLASS=com.callstack.react.brownfield.plugin.RNBrownfieldPlugin

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ 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.GradleExclude
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.shared.gradleExcludes
import com.callstack.react.brownfield.utils.AndroidArchiveLibrary
import com.callstack.react.brownfield.utils.DirectoryManager
import com.callstack.react.brownfield.utils.Extension
Expand All @@ -33,6 +35,24 @@ import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.ProjectConfigurationException

/**
* Coordinates that must never be published: embedded in the AAR (not resolvable from Maven), or
* excluded by the brownfield module's own Gradle rules.
*/
internal fun hardExcludePredicate(
project: Project,
expoPublishingHelper: ExpoPublishingHelper?,
artifacts: List<UnresolvedArtifactInfo>,
expoProjects: List<ExpoGradleProjectProjection>,
excludes: List<GradleExclude>,
): (String, String) -> Boolean =
{ groupId, artifactId ->
(expoPublishingHelper?.shouldExcludeDependency(groupId, artifactId) ?: (groupId == project.rootProject.name)) ||
artifacts.any { it.moduleGroup == groupId && it.moduleName == artifactId } ||
expoProjects.any { it.publication?.groupId == groupId && it.publication?.artifactId == artifactId } ||
excludes.any { it.matches(groupId, artifactId) }
}

class RNBrownfieldPlugin : Plugin<Project> {
private lateinit var extension: Extension
private lateinit var project: Project
Expand Down Expand Up @@ -140,11 +160,8 @@ class RNBrownfieldPlugin : Plugin<Project> {
// 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 } ||
expoProjects.any { it.publication?.groupId == groupId && it.publication?.artifactId == artifactId }
}
val excludes = gradleExcludes(project)
val hardExcludePredicate = hardExcludePredicate(project, expoPublishingHelper, artifacts, expoProjects, excludes)
dropHardExcludedDependencies(transitiveDeps, hardExcludePredicate)

Logging.log(
Expand All @@ -155,7 +172,7 @@ class RNBrownfieldPlugin : Plugin<Project> {
hardExcludePredicate(groupId, artifactId) || rncSupersededCoordinates.contains(groupId to artifactId)
}

injector.configure(transitiveDeps, removalPredicate)
injector.configure(transitiveDeps, removalPredicate, excludes)
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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.callstack.react.brownfield.shared

import org.gradle.api.Project

/**
* The variant-independent configurations that feed what the host app gets. A variant's own
* (`debugRuntimeClasspath`) would leak into every variant, since the published list is shared, and a
* tool's (lint, detekt) may exclude things the app still needs.
*/
private val PUBLISHED_CONFIG_NAMES = TRANSITIVE_DEPENDENCY_CONFIG_NAMES + "embed"

/**
* The configuration-level excludes that keep a dependency out of the brownfield module's build.
* The plugin reads what embedded libraries declare, not what Gradle resolves, so without these an
* excluded dependency would still be published and the host app would resolve it. `:app`'s rules
* are not read: they describe the standalone RN app, which may drop things the host needs.
*/
internal fun gradleExcludes(project: Project): List<GradleExclude> =
project.configurations
.filter { it.name in PUBLISHED_CONFIG_NAMES }
.flatMap { it.excludeRules }
.map { GradleExclude(it.group, it.module) }
.distinct()

/** One exclude rule. Gradle types both parts as non-null, but a rule without one leaves it null. */
internal data class GradleExclude(val group: String?, val module: String?) {
fun matches(
groupId: String,
artifactId: String,
) = (group == null || group == groupId) && (module == null || module == artifactId)
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import org.gradle.api.publish.tasks.GenerateModuleMetadata
internal fun mutatePomDependenciesNode(
dependenciesNode: Node,
dependencies: VersionMediatingDependencySet,
excludes: List<GradleExclude> = emptyList(),
shouldExclude: (groupId: String, artifactId: String) -> Boolean,
) {
dependenciesNode.children()
Expand Down Expand Up @@ -49,6 +50,21 @@ internal fun mutatePomDependenciesNode(
childTags.forEach { (tagName, tagValue) ->
newDepNode.appendNode(tagName, tagValue)
}
appendExclusions(newDepNode, excludes)
}
}
}

private fun appendExclusions(
dependencyNode: Node,
excludes: List<GradleExclude>,
) {
if (excludes.isEmpty()) return
val exclusionsNode = dependencyNode.appendNode("exclusions")
excludes.forEach { exclude ->
exclusionsNode.appendNode("exclusion").apply {
appendNode("groupId", exclude.group ?: "*")
appendNode("artifactId", exclude.module ?: "*")
}
}
}
Expand All @@ -69,6 +85,7 @@ internal fun resolveOrCreateDependenciesNode(root: Node): Node =
internal fun mutateModuleJsonVariants(
json: Map<*, *>,
dependencies: VersionMediatingDependencySet,
excludes: List<GradleExclude> = emptyList(),
shouldExclude: (groupId: String, artifactId: String) -> Boolean,
) {
@Suppress("UNCHECKED_CAST")
Expand Down Expand Up @@ -98,6 +115,9 @@ internal fun mutateModuleJsonVariants(
dependencyToAdd.version?.let { version ->
put("version", mapOf("requires" to version))
}
if (excludes.isNotEmpty()) {
put("excludes", excludes.map { mapOf("group" to (it.group ?: "*"), "module" to (it.module ?: "*")) })
}
},
)
}
Expand All @@ -116,6 +136,7 @@ internal fun mutateModuleJsonVariants(
class PublishingMetadataInjector(private val project: Project) {
private var dependencies = VersionMediatingDependencySet()
private var shouldExclude: (groupId: String, artifactId: String) -> Boolean = { _, _ -> false }
private var excludes: List<GradleExclude> = emptyList()
private var enabled = false

init {
Expand All @@ -124,12 +145,16 @@ class PublishingMetadataInjector(private val project: Project) {
}

/** Supplies the dependencies to inject and enables injection on the hooks registered in [init]. */
fun configure(
internal fun configure(
dependencies: VersionMediatingDependencySet,
shouldExclude: (groupId: String, artifactId: String) -> Boolean,
excludes: List<GradleExclude>,
) {
this.dependencies = dependencies
this.shouldExclude = shouldExclude
// Gradle writes the module's excludes onto the dependencies it declares; these are injected
// later, so they need them too, or an excluded library could still arrive through one.
this.excludes = excludes
this.enabled = true
}

Expand All @@ -148,7 +173,7 @@ class PublishingMetadataInjector(private val project: Project) {
if (!moduleFile.exists()) return@forEach

val json = moduleFile.inputStream().use { JsonSlurper().parse(it) as Map<*, *> }
mutateModuleJsonVariants(json, dependencies, shouldExclude)
mutateModuleJsonVariants(json, dependencies, excludes, shouldExclude)
moduleFile.writer().use {
it.write(JsonOutput.prettyPrint(JsonOutput.toJson(json)))
}
Expand All @@ -172,7 +197,7 @@ class PublishingMetadataInjector(private val project: Project) {

val root = it.asNode()
val dependenciesNode = resolveOrCreateDependenciesNode(root)
mutatePomDependenciesNode(dependenciesNode, dependencies, shouldExclude)
mutatePomDependenciesNode(dependenciesNode, dependencies, excludes, shouldExclude)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.callstack.react.brownfield.plugin

import com.callstack.react.brownfield.shared.gradleExcludes
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.assertFalse
import kotlin.test.assertTrue

class HardExcludePredicateTest {
@TempDir
lateinit var tempDir: File

@Test
fun `never publishes what the brownfield module excludes, or its own subprojects`() {
val root = ProjectBuilder.builder().withName("MyApp").withProjectDir(tempDir).build()
val lib = ProjectBuilder.builder().withName("brownfieldlib").withParent(root).build()
lib.configurations.create("implementation")
lib.configurations.all { it.exclude(mapOf("group" to "com.caverock", "module" to "androidsvg")) }

val excluded = hardExcludePredicate(lib, null, emptyList(), emptyList(), gradleExcludes(lib))

assertTrue(excluded("com.caverock", "androidsvg"))
assertTrue(excluded("MyApp", "react-native-screens"))
assertFalse(excluded("androidx.core", "core-ktx"))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.callstack.react.brownfield.shared

import org.gradle.api.Project
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.assertFalse
import kotlin.test.assertTrue

class GradleExcludesTest {
@TempDir
lateinit var tempDir: File

private fun project(
name: String,
vararg configNames: String,
): Project =
ProjectBuilder.builder().withName(name).withProjectDir(File(tempDir, name)).build().also { project ->
configNames.forEach { project.configurations.create(it) }
}

private fun Project.excludeEverywhere(
group: String,
module: String? = null,
) = configurations.all { config ->
config.exclude(listOfNotNull("group" to group, module?.let { "module" to it }).toMap())
}

private fun excluded(
project: Project,
groupId: String,
artifactId: String,
) = gradleExcludes(project).any { it.matches(groupId, artifactId) }

@Test
fun `honors an exclude declared on every configuration`() {
val lib = project("lib", "implementation", "releaseRuntimeClasspath")
lib.excludeEverywhere("com.caverock", "androidsvg")

assertTrue(excluded(lib, "com.caverock", "androidsvg"))
assertFalse(excluded(lib, "com.caverock", "androidsvg-aar"))
}

@Test
fun `a group-only exclude matches every module of the group`() {
val lib = project("lib", "api")
lib.excludeEverywhere("com.caverock")

assertTrue(excluded(lib, "com.caverock", "androidsvg-aar"))
}

@Test
fun `ignores a variant-specific exclude`() {
val lib = project("lib", "implementation", "debugRuntimeClasspath")
lib.configurations.getByName("debugRuntimeClasspath").exclude(mapOf("group" to "com.caverock"))

assertFalse(excluded(lib, "com.caverock", "androidsvg"))
}

@Test
fun `honors an exclude on a single runtime configuration`() {
val lib = project("lib", "embed")
lib.configurations.getByName("embed").exclude(mapOf("group" to "com.caverock", "module" to "androidsvg"))

assertTrue(excluded(lib, "com.caverock", "androidsvg"))
}

@Test
fun `ignores configurations that do not feed the runtime`() {
val lib = project("lib", "implementation", "detekt")
lib.configurations.getByName("detekt").exclude(mapOf("group" to "org.jetbrains.kotlin"))

assertFalse(excluded(lib, "org.jetbrains.kotlin", "kotlin-stdlib"))
}

@Test
fun `matches nothing without excludes`() {
assertFalse(excluded(project("lib", "implementation"), "com.caverock", "androidsvg"))
}
}
Loading
Loading