Improve package.json search mechanism for codegenConfig support (#34298)

Summary:
The `codegenConfig` unified configuration for New Architecture on Android relies on the Gradle plugin finding the package.json correctly. Currently we use the `root` folder to resolve the package.json. This works fine when invoking the codegen for the app module, but it doesn't work well when invoking the codegen for modules.

This extends the algo to make sure we first, look for a `package.json` in `..` and fallback to the one in the root if not found.

## Changelog

[Internal] - Improve package.json search mechanism for codegenConfig support

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

Test Plan: It's hard to write a unit test for this as it's inside a lambda, I'll look into doing this though. I've tested this on RNNewArchitectureApp and it works fine.

Reviewed By: cipolleschi

Differential Revision: D38249663

Pulled By: cortinico

fbshipit-source-id: 3cfd6a31e9f75d7b19b15f77bbd5131af42be9d3
This commit is contained in:
Nicola Corti
2022-08-02 12:30:46 +01:00
committed by Lorenzo Sciandra
parent 64788cc9fe
commit 91fdd998d3
@@ -92,19 +92,24 @@ class ReactPlugin : Plugin<Project> {
// We're reading the package.json at configuration time to properly feed
// the `jsRootDir` @Input property of this task. Therefore, the
// parsePackageJson should be invoked here.
val parsedPackageJson =
extension.root.file("package.json").orNull?.asFile?.let {
JsonUtils.fromCodegenJson(it)
// parsePackageJson should be invoked inside this lambda.
// We look for `package.json` in the parent folder of this Gradle module
// (generally the case for library projects) or we fallback to looking into the `root`
// folder of a React Native project (generally the case for app projects).
val packageJson =
if (project.file("../package.json").exists()) {
project.file("../package.json")
} else {
extension.root.file("package.json").orNull?.asFile
}
val parsedPackageJson = packageJson?.let { JsonUtils.fromCodegenJson(it) }
val parsedJsRootDir =
parsedPackageJson?.codegenConfig?.jsSrcsDir?.let { relativePath ->
extension.root.dir(relativePath)
}
?: extension.jsRootDir
it.jsRootDir.set(parsedJsRootDir)
val jsSrcsDirInPackageJson = parsedPackageJson?.codegenConfig?.jsSrcsDir
if (jsSrcsDirInPackageJson != null) {
it.jsRootDir.set(File(packageJson.parentFile, jsSrcsDirInPackageJson))
} else {
it.jsRootDir.set(extension.jsRootDir)
}
}
// We create the task to generate Java code from schema.