Skip to content

Commit

Permalink
feat: do not import BuildConfig/R, but use FQDN reference (#871)
Browse files Browse the repository at this point in the history
* feat: replace {{ packageName }} in deps' packageImportPath

* chore: extract interpolating to a separate function

* feat: add support for templating in packageInstance too

* docs: add paragraphs about interpolation

* Update packages/platform-android/native_modules.gradle

* Fix GH whitespace changes

* Make the change backwards-compatible

Libraries already expect to be able to use R and BuildConfig
classes without having to worry about their packages. To match the
expectations the script will replace un-fully-qualified references
to fully-qualified.

* Update dependencies.md

* Update native_modules.gradle

* Update native_modules.gradle

Co-authored-by: Mike Grabowski <grabbou@gmail.com>
  • Loading branch information
sjchmiela and grabbou authored Mar 19, 2020
1 parent 4dbfc77 commit c98214a
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions packages/platform-android/native_modules.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,37 @@ class ReactNativeModules {
String packageClassInstances = ""

if (packages.size() > 0) {
packageImports = "import ${packageName}.BuildConfig;\nimport ${packageName}.R;\n\n"
packageImports = packageImports + packages.collect {
"// ${it.name}\n${it.packageImportPath}"
def interpolateDynamicValues = {
it
// Before adding the package replacement mechanism,
// BuildConfig and R classes were imported automatically
// into the scope of the file. We want to replace all
// non-FQDN references to those classes with the package name
// of the MainApplication.
//
// We want to match "R" or "BuildConfig":
// - new Package(R.string…),
// - Module.configure(BuildConfig);
// ^ hence including (BuildConfig|R)
// but we don't want to match "R":
// - new Package(getResources…),
// - new PackageR…,
// - new Royal…,
// ^ hence excluding \w before and after matches
// and "BuildConfig" that has FQDN reference:
// - Module.configure(com.acme.BuildConfig);
// ^ hence excluding . before the match.
.replaceAll(~/([^.\w])(BuildConfig|R)([^\w])/, {
wholeString, prefix, className, suffix ->
"${prefix}${packageName}.${className}${suffix}"
})
}
packageImports = packages.collect {
"// ${it.name}\n${interpolateDynamicValues(it.packageImportPath)}"
}.join('\n')
packageClassInstances = ",\n " + packages.collect { it.packageInstance }.join(",\n ")
packageClassInstances = ",\n " + packages.collect {
interpolateDynamicValues(it.packageInstance)
}.join(",\n ")
}

String generatedFileContents = generatedFileContentsTemplate
Expand Down

0 comments on commit c98214a

Please sign in to comment.