fix: Use FQCN to avoid collisions in PackageList.java (#54736)

Summary:
When two different React Native libraries export a package class with the same name but in different namespaces, the generated PackageList.java causes a compilation error due to ambiguous class references.

The current autolinking generates:
``` kotlin
import com.pikachu.NativeStorage;
import com.snowfox.NativeStorage;  // ❌ Compile error: NativeStorage is already defined

public ArrayList<ReactPackage> getPackages() {
    return new ArrayList<>(Arrays.<ReactPackage>asList(
        new MainReactPackage(mConfig),
        new NativeStorage(),  // ❌ Ambiguous reference
        new NativeStorage()   // ❌ Ambiguous reference
    ));
}
```
Solution:-
Use fully qualified class names (FQCN) instead of imports:
``` kotlin
// No imports needed
public ArrayList<ReactPackage> getPackages() {
    return new ArrayList<>(Arrays.<ReactPackage>asList(
        new MainReactPackage(mConfig),
        // pikachu-storage
        new com.pikachu.NativeStorage(),
        // snowfox-storage
        new com.snowfox.NativeStorage()
    ));
}
```

## Changelog:

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->
[ANDROID][FIXED]- Use FQCN to avoid collisions

Pull Request resolved: https://github.com/facebook/react-native/pull/54736

Test Plan:
Updated test.
Also tested on my app and RN tester
<img width="687" height="223" alt="image" src="https://github.com/user-attachments/assets/fe54d0c3-4ab4-4d74-a98f-97243851e8c4" />

CI will tell if build fails

Reviewed By: mdvacca

Differential Revision: D88157961

Pulled By: cortinico

fbshipit-source-id: 5fe072dcaed177af1036ca88d55870081a3f4205
This commit is contained in:
riteshshukla04 authored and meta-codesync[bot] committed 2025-12-03 09:26:55 -08:00
1 parent 41eace0093
commit 5bb3a6d68d
2 files changed
+67 -75

No files matched your search

@@ -34,11 +34,11 @@ abstract class GeneratePackageListTask : DefaultTask() {
JsonUtils.fromAutolinkingConfigJson(autolinkInputFile.get().asFile)
?: error(
"""
RNGP - Autolinking: Could not parse autolinking config file:
${autolinkInputFile.get().asFile.absolutePath}
The file is either missing or not containing valid JSON so the build won't succeed.
"""
RNGP - Autolinking: Could not parse autolinking config file:
${autolinkInputFile.get().asFile.absolutePath}
The file is either missing or not containing valid JSON so the build won't succeed.
"""
.trimIndent()
)
@@ -49,9 +49,8 @@ abstract class GeneratePackageListTask : DefaultTask() {
)
val androidPackages = filterAndroidPackages(model)
val packageImports = composePackageImports(packageName, androidPackages)
val packageClassInstance = composePackageInstance(packageName, androidPackages)
val generatedFileContents = composeFileContent(packageImports, packageClassInstance)
val generatedFileContents = composeFileContent(packageClassInstance)
val outputDir = generatedOutputDirectory.get().asFile
outputDir.mkdirs()
@@ -61,34 +60,49 @@ abstract class GeneratePackageListTask : DefaultTask() {
}
}
internal fun composePackageImports(
packageName: String,
packages: Map<String, ModelAutolinkingDependenciesPlatformAndroidJson>,
) =
packages.entries.joinToString("\n") { (name, dep) ->
val packageImportPath =
requireNotNull(dep.packageImportPath) {
"RNGP - Autolinking: Missing `packageImportPath` in `config` for dependency $name. This is required to generate the autolinking package list."
}
"// $name\n${interpolateDynamicValues(packageImportPath, packageName)}"
}
/**
* Extracts the fully qualified class name from an import statement. E.g., "import
* com.foo.bar.MyClass;" -> "com.foo.bar.MyClass"
*/
internal fun extractFqcnFromImport(importStatement: String): String? {
val match = Regex("import\\s+([\\w.]+)\\s*;").find(importStatement)
return match?.groupValues?.get(1)
}
internal fun composePackageInstance(
packageName: String,
packages: Map<String, ModelAutolinkingDependenciesPlatformAndroidJson>,
) =
if (packages.isEmpty()) {
""
} else {
",\n " +
packages.entries.joinToString(",\n ") { (name, dep) ->
val packageInstance =
requireNotNull(dep.packageInstance) {
"RNGP - Autolinking: Missing `packageInstance` in `config` for dependency $name. This is required to generate the autolinking package list."
}
interpolateDynamicValues(packageInstance, packageName)
}
}
): String {
if (packages.isEmpty()) {
return ""
}
val instances =
packages.entries.map { (name, dep) ->
val packageInstance =
requireNotNull(dep.packageInstance) {
"RNGP - Autolinking: Missing `packageInstance` in `config` for dependency $name. This is required to generate the autolinking package list."
}
val packageImportPath = dep.packageImportPath
val interpolated = interpolateDynamicValues(packageInstance, packageName)
// Use FQCN to avoid class name collisions between different packages
val fqcn = extractFqcnFromImport(interpolateDynamicValues(packageImportPath, packageName))
val fqcnInstance =
if (fqcn != null) {
val className = fqcn.substringAfterLast('.')
// Replace the short class name with FQCN in the instance
interpolated.replace(Regex("\\b${Regex.escape(className)}\\b")) { fqcn }
} else {
interpolated
}
// Add comment with package name before each instance
"// $name\n $fqcnInstance"
}
return ",\n " + instances.joinToString(",\n ")
}
internal fun filterAndroidPackages(
model: ModelAutolinkingConfigJson?
@@ -101,10 +115,8 @@ abstract class GeneratePackageListTask : DefaultTask() {
.associate { it.name to checkNotNull(it.platforms?.android) }
}
internal fun composeFileContent(packageImports: String, packageClassInstance: String): String =
generatedFileContentsTemplate
.replace("{{ packageImports }}", packageImports)
.replace("{{ packageClassInstances }}", packageClassInstance)
internal fun composeFileContent(packageClassInstance: String): String =
generatedFileContentsTemplate.replace("{{ packageClassInstances }}", packageClassInstance)
companion object {
const val GENERATED_FILENAME = "com/facebook/react/PackageList.java"
@@ -148,8 +160,6 @@ abstract class GeneratePackageListTask : DefaultTask() {
import java.util.Arrays;
import java.util.ArrayList;
{{ packageImports }}
@SuppressWarnings("deprecation")
public class PackageList {
private Application application;
@@ -43,29 +43,17 @@ class GeneratePackageListTaskTest {
}
@Test
fun composePackageImports_withNoPackages_returnsEmpty() {
fun extractFqcnFromImport_withValidImport_returnsClassName() {
val task = createTestTask<GeneratePackageListTask>()
val packageName = "com.facebook.react"
val result = task.composePackageImports(packageName, emptyMap())
assertThat(result).isEqualTo("")
val result = task.extractFqcnFromImport("import com.facebook.react.APackage;")
assertThat(result).isEqualTo("com.facebook.react.APackage")
}
@Test
fun composePackageImports_withPackages_returnsImportCorrectly() {
fun extractFqcnFromImport_withInvalidImport_returnsNull() {
val task = createTestTask<GeneratePackageListTask>()
val packageName = "com.facebook.react"
val result = task.composePackageImports(packageName, testDependencies)
assertThat(result)
.isEqualTo(
"""
// @react-native/a-package
import com.facebook.react.aPackage;
// @react-native/another-package
import com.facebook.react.anotherPackage;
"""
.trimIndent()
)
val result = task.extractFqcnFromImport("invalid import statement")
assertThat(result).isNull()
}
@Test
@@ -77,7 +65,7 @@ class GeneratePackageListTaskTest {
}
@Test
fun composePackageInstance_withPackages_returnsImportCorrectly() {
fun composePackageInstance_withPackages_returnsFqcnCorrectly() {
val task = createTestTask<GeneratePackageListTask>()
val packageName = "com.facebook.react"
@@ -86,8 +74,10 @@ class GeneratePackageListTaskTest {
.isEqualTo(
"""
,
new APackage(),
new AnotherPackage()
// @react-native/a-package
new com.facebook.react.APackage(),
// @react-native/another-package
new com.facebook.react.AnotherPackage()
"""
.trimIndent()
)
@@ -226,10 +216,8 @@ class GeneratePackageListTaskTest {
@Test
fun composeFileContent_withNoPackages_returnsValidFile() {
val task = createTestTask<GeneratePackageListTask>()
val packageName = "com.facebook.react"
val imports = task.composePackageImports(packageName, emptyMap())
val instance = task.composePackageInstance(packageName, emptyMap())
val result = task.composeFileContent(imports, instance)
val instance = task.composePackageInstance("com.facebook.react", emptyMap())
val result = task.composeFileContent(instance)
// language=java
assertThat(result)
.isEqualTo(
@@ -246,8 +234,6 @@ class GeneratePackageListTaskTest {
import java.util.Arrays;
import java.util.ArrayList;
@SuppressWarnings("deprecation")
public class PackageList {
private Application application;
@@ -305,9 +291,8 @@ class GeneratePackageListTaskTest {
fun composeFileContent_withPackages_returnsValidFile() {
val task = createTestTask<GeneratePackageListTask>()
val packageName = "com.facebook.react"
val imports = task.composePackageImports(packageName, testDependencies)
val instance = task.composePackageInstance(packageName, testDependencies)
val result = task.composeFileContent(imports, instance)
val result = task.composeFileContent(instance)
// language=java
assertThat(result)
.isEqualTo(
@@ -324,11 +309,6 @@ class GeneratePackageListTaskTest {
import java.util.Arrays;
import java.util.ArrayList;
// @react-native/a-package
import com.facebook.react.aPackage;
// @react-native/another-package
import com.facebook.react.anotherPackage;
@SuppressWarnings("deprecation")
public class PackageList {
private Application application;
@@ -374,8 +354,10 @@ class GeneratePackageListTaskTest {
public ArrayList<ReactPackage> getPackages() {
return new ArrayList<>(Arrays.<ReactPackage>asList(
new MainReactPackage(mConfig),
new APackage(),
new AnotherPackage()
// @react-native/a-package
new com.facebook.react.APackage(),
// @react-native/another-package
new com.facebook.react.AnotherPackage()
));
}
}
@@ -389,7 +371,7 @@ class GeneratePackageListTaskTest {
"@react-native/a-package" to
ModelAutolinkingDependenciesPlatformAndroidJson(
sourceDir = "./a/directory",
packageImportPath = "import com.facebook.react.aPackage;",
packageImportPath = "import com.facebook.react.APackage;",
packageInstance = "new APackage()",
buildTypes = emptyList(),
libraryName = "aPackage",
@@ -399,7 +381,7 @@ class GeneratePackageListTaskTest {
"@react-native/another-package" to
ModelAutolinkingDependenciesPlatformAndroidJson(
sourceDir = "./another/directory",
packageImportPath = "import com.facebook.react.anotherPackage;",
packageImportPath = "import com.facebook.react.AnotherPackage;",
packageInstance = "new AnotherPackage()",
buildTypes = emptyList(),
libraryName = "anotherPackage",