-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
build.gradle
1017 lines (904 loc) · 38.2 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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import com.android.Version
import org.apache.tools.ant.filters.ReplaceTokens
import java.nio.file.Paths
/**
* 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 safeAppExtGet(prop, fallback) {
if (findProject(':app') == null) {
return fallback
}
def appProject = project(':app')
appProject?.ext?.has(prop) ? appProject.ext.get(prop) : fallback
}
def resolveBuildType() {
Gradle gradle = getGradle()
String tskReqStr = gradle.getStartParameter().getTaskRequests()['args'].toString()
return tskReqStr.contains('Release') ? 'release' : 'debug'
}
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 safeAppExtGet("isReanimatedExampleApp", false) || System.getenv("REANIMATED_PACKAGE_BUILD") == "1"
}
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() {
def reactNativeLocation = safeAppExtGet("REACT_NATIVE_NODE_MODULES_DIR", null)
if (reactNativeLocation != null) {
return file(reactNativeLocation)
}
if (isDeveloperMode()) {
return file("$projectDir/../${getPlaygroundAppName()}/node_modules/react-native")
}
// monorepo workaround
// react-native can be hoisted or in project's own node_modules
def reactNativeFromProjectNodeModules = file("${rootProject.projectDir}/../node_modules/react-native")
if (reactNativeFromProjectNodeModules.exists()) {
return reactNativeFromProjectNodeModules
}
def reactNativeFromNodeModulesWithReanimated = file("${projectDir}/../../react-native")
if (reactNativeFromNodeModulesWithReanimated.exists()) {
return reactNativeFromNodeModulesWithReanimated
}
throw new Exception(
"[Reanimated] Unable to resolve react-native location in " +
"node_modules. You should project extension property (in app/build.gradle) " +
"`REACT_NATIVE_NODE_MODULES_DIR` with path to 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
}
def shouldAssertNoMultipleInstances() {
if (rootProject.hasProperty("disableMultipleInstancesCheck")) {
return rootProject.property("disableMultipleInstancesCheck") != "true"
} else {
return true
}
}
def findReanimatedInstancesForPath(String path) {
return fileTree(path) {
include "**/react-native-reanimated/package.json"
exclude "**/.yarn/**"
exclude {{ file, attr -> attr.isSymbolicLink() }}
}.files
}
def assertNoMultipleInstances() {
// Assert there are no multiple installations of Reanimated
Set<File> files
if (projectDir.path.contains(rootDir.parent)) {
// standard app
files = findReanimatedInstancesForPath(rootDir.parent + "/node_modules")
} else {
// monorepo
files = findReanimatedInstancesForPath(rootDir.parent + "/node_modules")
files.addAll(
findReanimatedInstancesForPath(file(projectDir.parent).parent)
)
}
if (files.size() > 1) {
String parsedLocation = files.stream().map({
File file -> "- " + file.toString().replace("/package.json", "")
}).collect().join("\n")
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)
}
}
boolean CLIENT_SIDE_BUILD = resolveClientSideBuild()
if (CLIENT_SIDE_BUILD) {
configurations.maybeCreate("default")
}
def reactNativeRootDir = resolveReactNativeDirectory()
def reactProperties = new Properties()
file("$reactNativeRootDir/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_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME")
def REACT_NATIVE_MINOR_VERSION = REACT_NATIVE_VERSION.split("\\.")[1].toInteger()
def FBJNI_VERSION = "0.3.0"
def REANIMATED_PACKAGE_BUILD = System.getenv("REANIMATED_PACKAGE_BUILD")
// 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 customDownloadsDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR")
def downloadsDir = customDownloadsDir ? new File(customDownloadsDir) : new File("$buildDir/downloads")
def thirdPartyNdkDir = new File("$buildDir/third-party-ndk")
def reactNativeThirdParty = new File("$reactNativeRootDir/ReactAndroid/src/main/jni/third-party")
def reactNativeAndroidDownloadDir = new File("$reactNativeRootDir/ReactAndroid/build/downloads")
def _stackProtectorFlag = true
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 (REACT_NATIVE_MINOR_VERSION >= 69) {
return Paths.get(reactNativeRootDir.path, "sdks", "hermes")
} else {
return Paths.get(reactNativeRootDir.path, "..", "hermes-engine")
}
} else if (JS_RUNTIME == "v8") {
return findProject(":react-native-v8").getProjectDir().getParent()
} else {
return Paths.get(reactNativeRootDir.path, "ReactCommon", "jsi")
}
}.call()
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}
def detectAAR(Integer rnMinorVersion, String engine) { // Reanimated2 only
def rnMinorVersionCopy = rnMinorVersion
def aar = file("react-native-reanimated-${rnMinorVersionCopy}-${engine}.aar")
if (aar.exists()) {
println "AAR for react-native-reanimated has been found\n$aar"
return aar
} else {
while (!aar.exists() && rnMinorVersionCopy >= 63) {
rnMinorVersionCopy -= 1
aar = file("react-native-reanimated-${rnMinorVersionCopy}-${engine}.aar")
}
if (rnMinorVersionCopy < 63) {
println "No AAR for react-native-reanimated found. Attempting to build from source."
} else { // aar exists, but was build for lower react-native version
println "\n\n\n"
println "****************************************************************************************"
println "\n\n\n"
println "WARNING reanimated - no version-specific reanimated AAR for react-native version $minor found."
println "Falling back to AAR for react-native version $rnMinorVersionCopy."
println "The react-native JSI interface is not ABI-safe yet, this may result in crashes."
println "Please post a pull request to implement support for react-native version $minor to the reanimated repo."
println "Thanks!"
println "\n\n\n"
println "****************************************************************************************"
return aar
}
}
return null
}
def isUserDemandToBuildFromSource() { // Reanimated2 only
def buildFromSourceConf = false
rootProject.getSubprojects().forEach({project ->
if (project.plugins.hasPlugin("com.android.application")) {
if (
project.ext.has("reanimated")
&& project.ext.reanimated.buildFromSource
) {
buildFromSourceConf = true
}
}
})
return buildFromSourceConf
}
def shouldBuildFromSource(aar, jsRuntimeName) { // Reanimated2 only
if (jsRuntimeName == "v8") {
return true
}
else if (isDeveloperMode()) {
// Example app
return true
}
else if (isUserDemandToBuildFromSource()) {
// on user demand
return true
}
else if (aar != null) {
// when binary exist
return false
}
// when binary is not found
return true
}
def getTaskByPath(
project,
String appName,
String secondPart,
String flavorString,
String lastPart
) { // Reanimated2 only
String pathName = "${appName}:${secondPart}${flavorString}${lastPart}"
Task task = project.getTasks().findByPath(pathName)
if (task != null) {
return task
}
pathName = "${appName}:${secondPart}${flavorString.capitalize()}${lastPart}"
return project.getTasks().findByPath(pathName)
}
def aar = detectAAR(REACT_NATIVE_MINOR_VERSION, JS_RUNTIME)
boolean BUILD_FROM_SOURCE = shouldBuildFromSource(aar, JS_RUNTIME)
if (!BUILD_FROM_SOURCE && !isNewArchitectureEnabled()) { // Reanimated2 only
if (REACT_NATIVE_MINOR_VERSION < 65) {
tasks.register("replaceSoTaskDebug", replaceSoTask)
tasks.register("replaceSoTaskRelease", replaceSoTask)
Task replaceSoTaskDebug = project.getTasks().findByPath(":react-native-reanimated:replaceSoTaskDebug")
Task replaceSoTaskRelease = project.getTasks().findByPath(":react-native-reanimated:replaceSoTaskRelease")
if (replaceSoTaskDebug != null && replaceSoTaskRelease != null) {
rootProject.getSubprojects().forEach({project ->
if (project.plugins.hasPlugin("com.android.application") && project.getProperties().get("android")) {
def projectProperties = project.getProperties()
def flavorString = getCurrentFlavor()
def reanimatedConf = projectProperties.get("reanimated")
if (
flavorString != "NOT-FOUND"
&& (!reanimatedConf || (reanimatedConf && !reanimatedConf.get("enablePackagingOptions")))
) {
replaceSoTask.appName = projectProperties.path
replaceSoTask.buildDir = projectProperties.buildDir
def appName = projectProperties.path
Task debugNativeLibsTask = getTaskByPath(project, appName, "merge", flavorString, "DebugNativeLibs")
Task debugDebugSymbolsTask = getTaskByPath(project, appName, "strip", flavorString, "DebugDebugSymbols")
Task releaseNativeLibsTask = getTaskByPath(project, appName, "merge", flavorString, "ReleaseNativeLibs")
Task releaseDebugSymbolsTask = getTaskByPath(project, appName, "strip", flavorString, "ReleaseDebugSymbols")
Task debugTask = getTaskByPath(project, appName, "package", flavorString, "Debug")
Task releaseTask = getTaskByPath(project, appName, "package", flavorString, "Release")
if (
debugNativeLibsTask != null && debugDebugSymbolsTask != null
&& releaseNativeLibsTask != null && releaseDebugSymbolsTask != null
&& debugTask != null && releaseTask != null
) {
replaceSoTaskDebug.dependsOn(debugNativeLibsTask, debugDebugSymbolsTask)
debugTask.dependsOn(replaceSoTaskDebug)
replaceSoTaskRelease.dependsOn(releaseNativeLibsTask, releaseDebugSymbolsTask)
releaseTask.dependsOn(replaceSoTaskRelease)
}
}
}
})
}
}
artifacts.add("default", aar)
}
// end if already loaded aar
if (!BUILD_FROM_SOURCE) {
return
}
// 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:7.3.0"
classpath "de.undercouch:gradle-download-task:5.0.1"
classpath "com.diffplug.spotless:spotless-plugin-gradle:6.11.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",
"-DREACT_NATIVE_MINOR_VERSION=${REACT_NATIVE_MINOR_VERSION}",
"-DANDROID_TOOLCHAIN=clang",
"-DBOOST_VERSION=${BOOST_VERSION}",
"-DREACT_NATIVE_DIR=${reactNativeRootDir.path}",
"-DJS_RUNTIME=${JS_RUNTIME}",
"-DJS_RUNTIME_DIR=${jsRuntimeDir}",
"-DCLIENT_SIDE_BUILD=${CLIENT_SIDE_BUILD}",
"-DIS_NEW_ARCHITECTURE_ENABLED=${isNewArchitectureEnabled()}",
"-DPLAYGROUND_APP_NAME=${getPlaygroundAppName()}",
"-DREANIMATED_PACKAGE_BUILD=${REANIMATED_PACKAGE_BUILD}"
abiFilters (*reactNativeArchitectures())
_stackProtectorFlag ? (cppFlags("-fstack-protector-all")) : null
}
}
buildConfigField("boolean", "IS_INTERNAL_BUILD", "false")
buildConfigField("int", "EXOPACKAGE_FLAGS", "0")
buildConfigField("int", "REACT_NATIVE_MINOR_VERSION", REACT_NATIVE_MINOR_VERSION.toString())
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
buildTypes {
debug {
externalNativeBuild {
cmake {
if (JS_RUNTIME == "hermes") {
arguments "-DHERMES_ENABLE_DEBUGGER=1"
} else {
arguments "-DHERMES_ENABLE_DEBUGGER=0"
}
}
}
}
release {
externalNativeBuild {
cmake {
arguments "-DHERMES_ENABLE_DEBUGGER=0"
}
}
}
}
lintOptions {
abortOnError false
}
packagingOptions {
doNotStrip resolveBuildType() == 'debug' ? "**/**/*.so" : ''
excludes = [
"META-INF",
"META-INF/**",
"**/libc++_shared.so",
"**/libfbjni.so",
"**/libjsi.so",
"**/libfolly_json.so",
"**/libfolly_runtime.so",
"**/libglog.so",
"**/libhermes.so",
"**/libhermes-executor-debug.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",
]
}
}
}
}
def assertionTask = task assertNoMultipleInstancesTask {
onlyIf { shouldAssertNoMultipleInstances() && CLIENT_SIDE_BUILD }
doFirst {
assertNoMultipleInstances()
}
}
tasks.preBuild {
dependsOn assertionTask
}
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/${REACT_NATIVE_MINOR_VERSION}")
if (patchDirectory.exists()) {
from ("${patchDirectory}") {
include "**/*.java"
}
into ("${projectDir}/src/main/java/com/swmansion/reanimated")
}
}
task createNativeDepsDirectories(dependsOn: applyJavaPatches) {
downloadsDir.mkdirs()
thirdPartyNdkDir.mkdirs()
}
def resolveTaskFactory(String taskName, String artifactLocalName, File reactNativeAndroidDownloadDir, File reanimatedDownloadDir) {
return tasks.create(name: taskName, dependsOn: createNativeDepsDirectories, type: Copy) {
from reactNativeAndroidDownloadDir
include artifactLocalName
into reanimatedDownloadDir
onlyIf {
// First we check whether the file is already in our download directory
if (file("$reanimatedDownloadDir/$artifactLocalName").isFile()) {
return false
}
// If it is not the case we check whether it was downloaded by ReactAndroid project
if (file("$reactNativeAndroidDownloadDir/$artifactLocalName").isFile()) {
return true
}
return false
}
}
}
Task resolveBoost = resolveTaskFactory("resolveBoost", "boost_${BOOST_VERSION}.tar.gz", reactNativeAndroidDownloadDir, downloadsDir)
Task resolveDoubleConversion = resolveTaskFactory(
"resolveDoubleConversion",
"double-conversion-${DOUBLE_CONVERSION_VERSION}.tar.gz",
reactNativeAndroidDownloadDir,
downloadsDir
)
Task resolveFolly = resolveTaskFactory("resolveFolly", "folly-${FOLLY_VERSION}.tar.gz", reactNativeAndroidDownloadDir, downloadsDir)
Task resolveGlog = resolveTaskFactory("resolveGlog", "glog-${GLOG_VERSION}.tar.gz", reactNativeAndroidDownloadDir, downloadsDir)
if (isNewArchitectureEnabled()) {
def reactNativeAndroidProject = findProject(":ReactAndroid")
if (reactNativeAndroidProject != null) {
reactNativeAndroidProject.afterEvaluate {
def resolveTasks = [resolveBoost, resolveGlog, resolveDoubleConversion, resolveFolly]
resolveTasks.forEach({ task ->
String reactAndroidDownloadTaskName = "download" + task.name.replace("resolve", "")
def reactAndroidDownloadTask = reactNativeAndroidProject.getTasks().findByName(reactAndroidDownloadTaskName)
if (reactAndroidDownloadTask != null) {
task.dependsOn(reactAndroidDownloadTask)
} else {
logger.warn("[Reanimated] Failed to find task named `$reactAndroidDownloadTaskName` in `:ReactAndroid` project." +
" Explicit dependency between it and $task.name task can not be set.")
}
})
}
} else {
throw new GradleScriptException("[Reanimated] Failed to find `:ReactAndroid` project. Explicit dependency between download tasks can not be set.")
}
}
task downloadBoost(dependsOn: resolveBoost, type: Download) {
def transformedVersion = BOOST_VERSION.replace("_", ".")
def artifactLocalName = "boost_${BOOST_VERSION}.tar.gz"
def srcUrl = "https://boostorg.jfrog.io/artifactory/main/release/${transformedVersion}/source/boost_${BOOST_VERSION}.tar.gz"
if (REACT_NATIVE_MINOR_VERSION < 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, artifactLocalName))
}
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: resolveDoubleConversion, 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: resolveFolly, 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: resolveGlog, 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 (REACT_NATIVE_MINOR_VERSION >= 69 && !isNewArchitectureEnabled()) {
// copied from `react-native/ReactAndroid/hermes-engine/build.gradle`
def downloadDir = customDownloadsDir ? new File(customDownloadsDir) : 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 RelativePath(!file.isDirectory(), file.relativePath.segments.drop(1))
}
}
}
into(hermesDir)
}
}
task prepareHermes() {
if (REACT_NATIVE_MINOR_VERSION >= 69) {
if (!isNewArchitectureEnabled()) {
dependsOn(unzipHermes)
}
doLast {
// e.g. hermes-engine-0.70.0-rc.1-debug.aar
def hermesAAR = file(
"$reactNativeRootDir/android/com/facebook/react/hermes-engine/" +
"${REACT_NATIVE_VERSION}/hermes-engine-${REACT_NATIVE_VERSION}-" +
"${resolveBuildType()}.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 "$reactNativeRootDir/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-${resolveBuildType()}.aar") // e.g. hermes-debug.aar
if (!hermesAAR.exists()) {
throw new GradleScriptException("The hermes-engine npm package is missing \"android/hermes-${resolveBuildType()}.aar\"", null)
}
def soFiles = zipTree(hermesAAR).matching({ it.include "**/*.so" })
copy {
from soFiles
from "$reactNativeRootDir/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("$reactNativeRootDir/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 "$reactNativeRootDir/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 "$reactNativeRootDir/ReactAndroid/src/main/jni/first-party/$packageName/"
include "jni/**/*.so"
}
}
}
}
task packageNdkLibs(type: Copy) {
from("$buildDir/reanimated-ndk/all")
include("**/libreanimated.so")
if(REACT_NATIVE_MINOR_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 "$reactNativeRootDir/android"
}
maven {
// Android JSC is installed from npm
url "$reactNativeRootDir/../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"
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("$reactNativeRootDir/../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 (REACT_NATIVE_MINOR_VERSION < 69) {
rnAarMatcher = "**/**/*.aar"
}
def rnAAR = fileTree("$reactNativeRootDir/android").matching({ it.include rnAarMatcher }).singleFile
def file = rnAAR.absoluteFile
def packageName = file.name.tokenize('-')[0]
copy {
from zipTree(file)
into "$reactNativeRootDir/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")
|| task.name.contains("generateJsonModel")
)
) })
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")