/
build.gradle
740 lines (656 loc) · 27.4 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
import com.android.Version
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.Path
import org.apache.tools.ant.filters.ReplaceTokens
import groovy.json.JsonSlurper
import java.util.stream.Stream
/**
* Finds the path of the installed npm package with the given name using Node's
* module resolution algorithm, which searches "node_modules" directories up to
* the file system root. This handles various cases, including:
*
* - Working in the open-source RN repo:
* Gradle: /path/to/react-native/ReactAndroid
* Node module: /path/to/react-native/node_modules/[package]
*
* - Installing RN as a dependency of an app and searching for hoisted
* dependencies:
* Gradle: /path/to/app/node_modules/react-native/ReactAndroid
* Node module: /path/to/app/node_modules/[package]
*
* - Working in a larger repo (e.g., Facebook) that contains RN:
* Gradle: /path/to/repo/path/to/react-native/ReactAndroid
* Node module: /path/to/repo/node_modules/[package]
*
* The search begins at the given base directory (a File object). The returned
* path is a string.
*/
static def findNodeModulePath(baseDir, packageName) {
def basePath = baseDir.toPath().normalize()
// Node's module resolution algorithm searches up to the root directory,
// after which the base path will be null
while (basePath) {
def candidatePath = Paths.get(basePath.toString(), "node_modules", packageName)
if (candidatePath.toFile().exists()) {
return candidatePath.toString()
}
basePath = basePath.getParent()
}
return null
}
def safeExtGet(prop, fallback) {
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}
def resolveBuildType() {
def buildType = "debug"
tasks.all({ task ->
if (task.name == "buildCMakeRelease") {
buildType = "release"
}
})
return buildType
}
def resolveClientSideBuild() {
def clientSideBuild = System.getenv("CLIENT_SIDE_BUILD")
if (clientSideBuild != null) {
return clientSideBuild == "True"
}
if (hasProperty("clientSideBuild")) {
return property("clientSideBuild") == "true"
}
if (isDeveloperMode()) {
return false
}
return true
}
def isDeveloperMode() {
// developer mode, to run Example app
return file("$projectDir/../node_modules/react-native/package.json").exists()
}
def isNewArchitectureEnabled() {
// To opt-in for the New Architecture, you can either:
// - Set `newArchEnabled` to true inside the `gradle.properties` file
// - Invoke gradle with `-newArchEnabled=true`
// - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}
def resolveReactNativeDirectory() {
if (isDeveloperMode()) {
return file("$projectDir/../${getPlaygroundAppName()}/node_modules/react-native")
}
return file("$projectDir/../../react-native")
}
def getPlaygroundAppName() { // only for the development
String playgroundAppName = ""
try {
rootProject.getSubprojects().forEach({project ->
if (project.plugins.hasPlugin("com.android.application")) {
var projectCatalogAbsolutePath = project.projectDir.toString().replace("/android/app", "")
var slashPosition = projectCatalogAbsolutePath.lastIndexOf("/")
playgroundAppName = projectCatalogAbsolutePath.substring(slashPosition + 1)
}
})
} catch(_) {
return "NOT_FOUND"
}
return playgroundAppName
}
boolean CLIENT_SIDE_BUILD = resolveClientSideBuild()
if (CLIENT_SIDE_BUILD) {
configurations.maybeCreate("default")
List<Path> paths = Files.find(
Paths.get(rootDir.parent),
Integer.MAX_VALUE,
{path, fileAttributes -> path.toString().endsWith("/react-native-reanimated/package.json") }
).toArray()
String parsedLocation = ""
def libInstancesCount = 0
for (def path in paths) {
parsedLocation += "- " + path.toString().replace("/package.json", "\n")
libInstancesCount++
}
if (libInstancesCount > 1) {
String exceptionMessage = "\nMultiple versions of Reanimated were detected. Only one instance of react-native-reanimated can be installed in a project. You need to resolve the conflict manually. Check out the documentation: https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/troubleshooting#multiple-versions-of-reanimated-were-detected \n\nConflict between: \n" + parsedLocation + "\n";
throw new Exception(exceptionMessage)
}
}
def reactNative = resolveReactNativeDirectory()
def reactNativeManifest = file("$reactNative/package.json")
def reactNativeManifestAsJson = new JsonSlurper().parseText(reactNativeManifest.text)
def reactNativeVersion = reactNativeManifestAsJson.version as String
def (major, minor, patch) = reactNativeVersion.tokenize('.')
def rnMinorVersion = Integer.parseInt(minor)
def localProps = new Properties()
def localPropertiesFile = file("local.properties")
if (localPropertiesFile.exists()) {
localProps.load(new InputStreamReader(new FileInputStream(localPropertiesFile), "UTF-8"))
}
def debugNativeLibraries = localProps.getProperty('NATIVE_DEBUG_ON', 'FALSE').toBoolean()
def reactProperties = new Properties()
file("$reactNative/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
def BOOST_VERSION = reactProperties.getProperty("BOOST_VERSION")
def DOUBLE_CONVERSION_VERSION = reactProperties.getProperty("DOUBLE_CONVERSION_VERSION")
def FOLLY_VERSION = reactProperties.getProperty("FOLLY_VERSION")
def GLOG_VERSION = reactProperties.getProperty("GLOG_VERSION")
def REACT_VERSION = reactProperties.getProperty("VERSION_NAME").split("\\.")[1].toInteger()
def FBJNI_VERSION = "0.3.0"
// We download various C++ open-source dependencies into downloads.
// We then copy both the downloaded code and our custom makefiles and headers into third-party-ndk.
// After that we build native code from src/main/jni with module path pointing at third-party-ndk.
def downloadsDir = new File("$buildDir/downloads")
def thirdPartyNdkDir = new File("$buildDir/third-party-ndk")
def reactNativeThirdParty = new File("$reactNative/ReactAndroid/src/main/jni/third-party")
def _stackProtectorFlag = true
def CMAKE_NODE_MODULES_DIR = CLIENT_SIDE_BUILD
? project.getProjectDir().getParentFile().getParent()
: Paths.get(project.getProjectDir().getParent(), getPlaygroundAppName(), "node_modules").toString()
def JS_RUNTIME = {
// Returns the js runtime explicitly requested in the environment variable
if (System.getenv("JS_RUNTIME")) {
return System.getenv("JS_RUNTIME")
}
// Detect js runtime from project setup
def defaultRuntimeType = "jsc";
def v8Project = rootProject.getSubprojects().find { project -> project.name == "react-native-v8" }
if (v8Project != null) {
return "v8"
}
def appProject = findProject(":app") ? project(":app") : null
return appProject?.ext?.react?.enableHermes ? "hermes" : defaultRuntimeType
}.call()
def jsRuntimeDir = {
if (JS_RUNTIME == "hermes") {
if (rnMinorVersion >= 69) {
return Paths.get(CMAKE_NODE_MODULES_DIR, "react-native", "sdks", "hermes")
} else {
return Paths.get(CMAKE_NODE_MODULES_DIR, "hermes-engine")
}
} else if (JS_RUNTIME == "v8") {
return findProject(":react-native-v8").getProjectDir().getParent()
} else {
return Paths.get(CMAKE_NODE_MODULES_DIR, "react-native", "ReactCommon", "jsi")
}
}.call()
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}
// You need to have following folders in this directory:
// - boost_1_63_0
// - double-conversion-1.1.6
// - folly-deprecate-dynamic-initializer
// - glog-0.3.5
def dependenciesPath = System.getenv("REACT_NATIVE_DEPENDENCIES")
// The Boost library is a very large download (>100MB).
// If Boost is already present on your system, define the REACT_NATIVE_BOOST_PATH env variable
// and the build will use that.
def boostPath = dependenciesPath ?: System.getenv("REACT_NATIVE_BOOST_PATH")
def follyReplaceContent = '''
ssize_t r;
do {
r = open(name, flags, mode);
} while (r == -1 && errno == EINTR);
return r;
'''
buildscript {
repositories {
google()
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.2"
classpath "de.undercouch:gradle-download-task:4.1.2"
classpath "com.diffplug.spotless:spotless-plugin-gradle:5.15.0"
}
}
if (project == rootProject) {
apply from: "spotless.gradle"
}
apply plugin: "com.android.library"
apply plugin: "maven-publish"
apply plugin: "de.undercouch.download"
android {
compileSdkVersion safeExtGet("compileSdkVersion", 30)
defaultConfig {
minSdkVersion safeExtGet("minSdkVersion", 16)
targetSdkVersion safeExtGet("targetSdkVersion", 30)
versionCode 1
versionName "1.0"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
externalNativeBuild {
cmake {
arguments "-DANDROID_STL=c++_shared",
"-DNATIVE_DEBUG=${debugNativeLibraries}",
"-DREACT_NATIVE_TARGET_VERSION=${REACT_VERSION}",
"-DANDROID_TOOLCHAIN=clang",
"-DBOOST_VERSION=${BOOST_VERSION}",
"-DNODE_MODULES_DIR=${CMAKE_NODE_MODULES_DIR}",
"-DJS_RUNTIME=${JS_RUNTIME}",
"-DJS_RUNTIME_DIR=${jsRuntimeDir}",
"-DCLIENT_SIDE_BUILD=${CLIENT_SIDE_BUILD}",
"-DIS_NEW_ARCHITECTURE_ENABLED=${isNewArchitectureEnabled()}",
"-DPLAYGROUND_APP_NAME=${getPlaygroundAppName()}",
"-DRNVERSION=${rnMinorVersion}"
abiFilters (*reactNativeArchitectures())
_stackProtectorFlag ? (cppFlags("-fstack-protector-all")) : null
}
}
buildConfigField("boolean", "IS_INTERNAL_BUILD", "false")
buildConfigField("int", "EXOPACKAGE_FLAGS", "0")
buildConfigField("int", "REACT_NATIVE_VERSION", rnMinorVersion.toString())
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
version "3.18.1"
}
}
lintOptions {
abortOnError false
}
packagingOptions {
println "Native libs debug enabled: ${debugNativeLibraries}"
doNotStrip debugNativeLibraries ? "**/**/*.so" : ''
excludes = [
"**/libc++_shared.so",
"**/libfbjni.so",
"**/libjsi.so",
"**/libfolly_json.so",
"**/libfolly_runtime.so",
"**/libglog.so",
"**/libhermes.so",
"**/libreactnativejni.so",
"**/libjscexecutor.so",
"**/libv8executor.so",
]
}
tasks.withType(JavaCompile) {
compileTask ->
compileTask.dependsOn(packageNdkLibs)
}
configurations {
extractHeaders
extractSO
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
// For some reason gradle only complains about the duplicated version of librrc_root and libreact_render libraries
// while there are more libraries copied in intermediates folder of the lib build directory, we exclude
// only the ones that make the build fail (ideally we should only include libreanimated but we
// are only allowed to specify exlude patterns)
exclude "**/libreact_render*.so"
exclude "**/librrc_root.so"
}
sourceSets.main {
java {
if (isNewArchitectureEnabled()) {
srcDirs += [
"src/fabric/java",
]
} else {
srcDirs += [
"src/paper/java",
]
}
}
}
}
task cleanCmakeCache() {
tasks.getByName("clean").dependsOn(cleanCmakeCache)
doFirst {
delete "${projectDir}/.cxx"
}
}
task printVersions {
println "Android gradle plugin: ${Version.ANDROID_GRADLE_PLUGIN_VERSION}"
println "Gradle: ${project.gradle.gradleVersion}"
}
task Log {
println("building Reanimated2")
}
task applyJavaPatches(type: Copy) {
def patchDirectory = file("${projectDir}/rnVersionPatch/${rnMinorVersion}")
if (patchDirectory.exists()) {
from ("${patchDirectory}") {
include "**/*.java"
}
into ("${projectDir}/src/main/java/com/swmansion/reanimated")
}
}
task createNativeDepsDirectories(dependsOn: applyJavaPatches) {
downloadsDir.mkdirs()
thirdPartyNdkDir.mkdirs()
}
task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) {
def transformedVersion = BOOST_VERSION.replace("_", ".")
def srcUrl = "https://boostorg.jfrog.io/artifactory/main/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz"
if (rnMinorVersion < 69) {
srcUrl = "https://github.com/react-native-community/boost-for-react-native/releases/download/v${transformedVersion}-0/boost_${BOOST_VERSION}.tar.gz"
}
src(srcUrl)
onlyIfNewer(true)
overwrite(false)
dest(new File(downloadsDir, "boost_${BOOST_VERSION}.tar.gz"))
}
task prepareBoost(dependsOn: boostPath ? [] : [downloadBoost], type: Copy) {
from(boostPath ?: tarTree(resources.gzip(downloadBoost.dest)))
from("$reactNativeThirdParty/boost/Android.mk")
include("Android.mk", "boost_${BOOST_VERSION}/boost/**/*.hpp", "boost/boost/**/*.hpp")
includeEmptyDirs = false
into("$thirdPartyNdkDir/boost")
doLast {
file("$thirdPartyNdkDir/boost/boost").renameTo("$thirdPartyNdkDir/boost/boost_${BOOST_VERSION}")
}
}
task downloadDoubleConversion(dependsOn: createNativeDepsDirectories, type: Download) {
src("https://github.com/google/double-conversion/archive/v${DOUBLE_CONVERSION_VERSION}.tar.gz")
onlyIfNewer(true)
overwrite(false)
dest(new File(downloadsDir, "double-conversion-${DOUBLE_CONVERSION_VERSION}.tar.gz"))
}
task prepareDoubleConversion(dependsOn: dependenciesPath ? [] : [downloadDoubleConversion], type: Copy) {
from(dependenciesPath ?: tarTree(downloadDoubleConversion.dest))
from("$reactNativeThirdParty/double-conversion/Android.mk")
include("double-conversion-${DOUBLE_CONVERSION_VERSION}/src/**/*", "Android.mk")
filesMatching("*/src/**/*", { fname -> fname.path = "double-conversion/${fname.name}" })
includeEmptyDirs = false
into("$thirdPartyNdkDir/double-conversion")
}
task downloadFolly(dependsOn: createNativeDepsDirectories, type: Download) {
src("https://github.com/facebook/folly/archive/v${FOLLY_VERSION}.tar.gz")
onlyIfNewer(true)
overwrite(false)
dest(new File(downloadsDir, "folly-${FOLLY_VERSION}.tar.gz"))
}
task prepareFolly(dependsOn: dependenciesPath ? [] : [downloadFolly], type: Copy) {
from(dependenciesPath ?: tarTree(downloadFolly.dest))
from("$reactNativeThirdParty/folly/Android.mk")
include("folly-${FOLLY_VERSION}/folly/**/*", "Android.mk")
eachFile { fname -> fname.path = (fname.path - "folly-${FOLLY_VERSION}/") }
// Fixes problem with Folly failing to build on certain systems. See
// https://github.com/software-mansion/react-native-reanimated/issues/1024
filter { line -> line.replaceAll("return int\\(wrapNoInt\\(open, name, flags, mode\\)\\);", follyReplaceContent) }
includeEmptyDirs = false
into("$thirdPartyNdkDir/folly")
}
task downloadGlog(dependsOn: createNativeDepsDirectories, type: Download) {
src("https://github.com/google/glog/archive/v${GLOG_VERSION}.tar.gz")
onlyIfNewer(true)
overwrite(false)
dest(new File(downloadsDir, "glog-${GLOG_VERSION}.tar.gz"))
}
// Prepare glog sources to be compiled, this task will perform steps that normally should've been
// executed by automake. This way we can avoid dependencies on make/automake
task prepareGlog(dependsOn: dependenciesPath ? [] : [downloadGlog], type: Copy) {
duplicatesStrategy = "include"
from(dependenciesPath ?: tarTree(downloadGlog.dest))
from("$reactNativeThirdParty/glog/")
include("glog-${GLOG_VERSION}/src/**/*", "Android.mk", "config.h")
includeEmptyDirs = false
filesMatching("**/*.h.in") {
filter(ReplaceTokens, tokens: [
ac_cv_have_unistd_h : "1",
ac_cv_have_stdint_h : "1",
ac_cv_have_systypes_h : "1",
ac_cv_have_inttypes_h : "1",
ac_cv_have_libgflags : "0",
ac_google_start_namespace : "namespace google {",
ac_cv_have_uint16_t : "1",
ac_cv_have_u_int16_t : "1",
ac_cv_have___uint16 : "0",
ac_google_end_namespace : "}",
ac_cv_have___builtin_expect : "1",
ac_google_namespace : "google",
ac_cv___attribute___noinline : "__attribute__ ((noinline))",
ac_cv___attribute___noreturn : "__attribute__ ((noreturn))",
ac_cv___attribute___printf_4_5: "__attribute__((__format__ (__printf__, 4, 5)))"
])
it.path = (it.name - ".in")
}
into("$thirdPartyNdkDir/glog")
doLast {
copy {
from(fileTree(dir: "$thirdPartyNdkDir/glog", includes: ["stl_logging.h", "logging.h", "raw_logging.h", "vlog_is_on.h", "**/src/glog/log_severity.h"]).files)
includeEmptyDirs = false
into("$thirdPartyNdkDir/glog/exported/glog")
}
}
}
/*
Reanimated includes "hermes/hermes.h" header file in `NativeProxy.cpp`.
Previously, we used header files from `hermes-engine` package in `node_modules`.
Starting from React Native 0.69, Hermes is no longer distributed as package on NPM.
On the new architecture, Hermes is downloaded from GitHub and then compiled from sources.
However, on the old architecture, we need to download Hermes header files on our own
as well as unzip Hermes AAR in order to obtain `libhermes.so` shared library.
For more details, see https://reactnative.dev/architecture/bundled-hermes
or https://github.com/reactwg/react-native-new-architecture/discussions/4
*/
if (rnMinorVersion >= 69 && !isNewArchitectureEnabled()) {
// copied from `react-native/ReactAndroid/hermes-engine/build.gradle`
def reactNativeRootDir = resolveReactNativeDirectory()
def customDownloadDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR")
def downloadDir = customDownloadDir ? new File(customDownloadDir) : new File(reactNativeRootDir, "sdks/download")
// By default we are going to download and unzip hermes inside the /sdks/hermes folder
// but you can provide an override for where the hermes source code is located.
def hermesDir = System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR") ?: new File(reactNativeRootDir, "sdks/hermes")
def hermesVersion = "main"
def hermesVersionFile = new File(reactNativeRootDir, "sdks/.hermesversion")
if (hermesVersionFile.exists()) {
hermesVersion = hermesVersionFile.text
}
task downloadHermes(type: Download) {
src("https://github.com/facebook/hermes/tarball/${hermesVersion}")
onlyIfNewer(true)
overwrite(false)
dest(new File(downloadDir, "hermes.tar.gz"))
}
task unzipHermes(dependsOn: downloadHermes, type: Copy) {
from(tarTree(downloadHermes.dest)) {
eachFile { file ->
// We flatten the unzip as the tarball contains a `facebook-hermes-<SHA>`
// folder at the top level.
if (file.relativePath.segments.size() > 1) {
file.relativePath = new org.gradle.api.file.RelativePath(!file.isDirectory(), file.relativePath.segments.drop(1))
}
}
}
into(hermesDir)
}
}
task prepareHermes() {
if (rnMinorVersion >= 69) {
if (!isNewArchitectureEnabled()) {
dependsOn(unzipHermes)
}
doLast {
def hermesAAR = file("$reactNative/android/com/facebook/react/hermes-engine/$reactNativeVersion/hermes-engine-$reactNativeVersion-${resolveBuildType()}.aar") // e.g. hermes-engine-0.70.0-rc.1-debug.aar
if (!hermesAAR.exists()) {
throw new GradleScriptException("Could not find hermes-engine AAR", null)
}
def soFiles = zipTree(hermesAAR).matching({ it.include "**/*.so" })
copy {
from soFiles
from "$reactNative/ReactAndroid/src/main/jni/first-party/hermes/Android.mk"
into "$thirdPartyNdkDir/hermes"
}
}
} else {
doLast {
def hermesPackagePath = findNodeModulePath(projectDir, "hermes-engine")
if (!hermesPackagePath) {
throw new GradleScriptException("Could not find the hermes-engine npm package", null)
}
def hermesAAR = file("$hermesPackagePath/android/hermes-debug.aar")
if (!hermesAAR.exists()) {
throw new GradleScriptException("The hermes-engine npm package is missing \"android/hermes-debug.aar\"", null)
}
def soFiles = zipTree(hermesAAR).matching({ it.include "**/*.so" })
copy {
from soFiles
from "$reactNative/ReactAndroid/src/main/jni/first-party/hermes/Android.mk"
into "$thirdPartyNdkDir/hermes"
}
}
}
}
task prepareJSC {
doLast {
def jscPackagePath = findNodeModulePath(projectDir, "jsc-android")
if (!jscPackagePath) {
throw new GradleScriptException("Could not find the jsc-android npm package", null)
}
def jscDist = file("$jscPackagePath/dist")
if (!jscDist.exists()) {
throw new GradleScriptException("The jsc-android npm package is missing its \"dist\" directory", null)
}
def jscAAR = fileTree(jscDist).matching({ it.include "**/android-jsc/**/*.aar" }).singleFile
def soFiles = zipTree(jscAAR).matching({ it.include "**/*.so" })
def headerFiles = fileTree(jscDist).matching({ it.include "**/include/*.h" })
copy {
from(soFiles)
from(headerFiles)
from("$reactNative/ReactAndroid/src/main/jni/third-party/jsc/Android.mk")
filesMatching("**/*.h", { it.path = "JavaScriptCore/${it.name}" })
includeEmptyDirs(false)
into("$thirdPartyNdkDir/jsc")
}
}
}
task extractAARHeaders {
doLast {
configurations.extractHeaders.files.each {
def file = it.absoluteFile
def packageName = file.name.tokenize('-')[0]
copy {
from zipTree(file)
into "$reactNative/ReactAndroid/src/main/jni/first-party/$packageName/headers"
include "**/*.h"
}
}
}
}
task extractSOFiles {
doLast {
configurations.extractSO.files.each {
def file = it.absoluteFile
def packageName = file.name.tokenize('-')[0]
copy {
from zipTree(file)
into "$reactNative/ReactAndroid/src/main/jni/first-party/$packageName/"
include "jni/**/*.so"
}
}
}
}
task packageNdkLibs(type: Copy) {
from("$buildDir/reanimated-ndk/all")
include("**/libreanimated.so")
if(REACT_VERSION < 64) {
include("**/libturbomodulejsijni.so")
}
into("$projectDir/src/main/jniLibs")
}
repositories {
mavenCentral()
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$reactNative/android"
}
maven {
// Android JSC is installed from npm
url "$reactNative/../jsc-android/dist"
}
google()
}
dependencies {
// noinspection GradleDynamicVersion
implementation "com.facebook.yoga:proguard-annotations:1.19.0"
if (isDeveloperMode() && !isNewArchitectureEnabled()) {
implementation "com.facebook.fbjni:fbjni:" + FBJNI_VERSION
}
else {
implementation "com.facebook.fbjni:fbjni-java-only:" + FBJNI_VERSION
}
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.transition:transition:1.1.0"
if (rnMinorVersion > 66) {
implementation "androidx.core:core:1.7.0"
}
else {
implementation "androidx.core:core:1.6.0"
}
extractHeaders("com.facebook.fbjni:fbjni:" + FBJNI_VERSION + ":headers")
extractSO("com.facebook.fbjni:fbjni:" + FBJNI_VERSION)
def jscAAR = fileTree("$reactNative/../jsc-android/dist/org/webkit/android-jsc").matching({ it.include "**/**/*.aar" }).singleFile
extractSO(files(jscAAR))
}
task unpackReactNativeAAR {
def buildType = resolveBuildType()
def rnAarMatcher = "**/react-native/**/*${buildType}.aar"
if (rnMinorVersion < 69) {
rnAarMatcher = "**/**/*.aar"
}
def rnAAR = fileTree("$reactNative/android").matching({ it.include rnAarMatcher }).singleFile
def file = rnAAR.absoluteFile
def packageName = file.name.tokenize('-')[0]
copy {
from zipTree(file)
into "$reactNative/ReactAndroid/src/main/jni/first-party/$packageName/"
include "jni/**/*.so"
}
}
task downloadNdkBuildDependencies {
if (!boostPath) {
dependsOn(downloadBoost)
}
dependsOn(downloadDoubleConversion)
dependsOn(downloadFolly)
dependsOn(downloadGlog)
}
task prepareThirdPartyNdkHeaders(dependsOn:[downloadNdkBuildDependencies, prepareBoost, prepareDoubleConversion, prepareFolly, prepareGlog, unpackReactNativeAAR]) {
}
def nativeBuildDependsOn(dependsOnTask) {
def buildTasks = tasks.findAll({ task ->
!task.name.contains("Clean") && (task.name.contains("externalNative") || task.name.contains("CMake")) })
buildTasks.forEach { task -> task.dependsOn(dependsOnTask) }
}
afterEvaluate {
extractAARHeaders.dependsOn(prepareThirdPartyNdkHeaders)
extractSOFiles.dependsOn(prepareThirdPartyNdkHeaders)
nativeBuildDependsOn(prepareThirdPartyNdkHeaders)
nativeBuildDependsOn(extractAARHeaders)
nativeBuildDependsOn(extractSOFiles)
tasks.forEach({ task ->
if (task.name.contains("JniLibFolders")) {
task.dependsOn(packageNdkLibs)
}
})
if (JS_RUNTIME == "hermes") {
extractAARHeaders.dependsOn(prepareHermes)
extractSOFiles.dependsOn(prepareHermes)
} else if (JS_RUNTIME == "v8") {
def buildTasks = tasks.findAll({ task ->
!task.name.contains("Clean") && (task.name.contains("externalNative") || task.name.contains("CMake") || task.name.startsWith("generateJsonModel")) })
buildTasks.forEach { task ->
def buildType = task.name.endsWith('Debug') ? 'Debug' : 'Release'
task.dependsOn(":react-native-v8:copy${buildType}JniLibsProjectOnly")
}
}
}
if (CLIENT_SIDE_BUILD) {
def aarDir = "${buildDir}/outputs"
def aar = file("${aarDir}/android-debug.aar")
if (aar == null) {
throw GradleScriptException("AAR build failed. No AAR found in ${aarDir}.")
}
artifacts.add("default", aar)
}