-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathbuild.gradle
812 lines (682 loc) · 30.5 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
/*
* Script builds apk in release or debug mode
* To run:
* gradle assembleRelease -Prelease (release mode)
* gradle assembleDebug (debug mode -> default)
* Options:
* -Prelease //this flag will run build in release mode
* -PksPath=[path_to_keystore_file]
* -PksPassword=[password_for_keystore_file]
* -Palias=[alias_to_use_from_keystore_file]
* -Ppassword=[password_for_alias]
*
* -PtargetSdk=[target_sdk]
* -PbuildToolsVersion=[build_tools_version]
* -PsupportVersion=[support_version]
* -PcompileSdk=[compile_sdk_version]
*/
import groovy.json.JsonSlurper
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.regex.Matcher
import java.util.regex.Pattern
import java.security.MessageDigest
import javax.inject.Inject
apply plugin: "com.android.application"
def onlyX86 = project.hasProperty("onlyX86")
if (onlyX86) {
println "OnlyX86 build triggered."
}
//common
def BUILD_TOOLS_PATH = "$rootDir/build-tools"
def PASSED_TYPINGS_PATH = System.getenv("TNS_TYPESCRIPT_DECLARATIONS_PATH")
def TYPINGS_PATH = "$BUILD_TOOLS_PATH/typings"
if (PASSED_TYPINGS_PATH != null) {
TYPINGS_PATH = PASSED_TYPINGS_PATH
}
def PACKAGE_JSON = "package.json"
//static binding generator
def SBG_JAVA_DEPENDENCIES = "sbg-java-dependencies.txt"
def SBG_INPUT_FILE = "sbg-input-file.txt"
def SBG_OUTPUT_FILE = "sbg-output-file.txt"
def SBG_JS_PARSED_FILES = "sbg-js-parsed-files.txt"
def SBG_BINDINGS_NAME = "sbg-bindings.txt"
def SBG_INTERFACE_NAMES = "sbg-interface-names.txt"
def INPUT_JS_DIR = "$projectDir/src/main/assets/app"
def OUTPUT_JAVA_DIR = "$projectDir/src/main/java"
//metadata generator
def MDG_OUTPUT_DIR = "mdg-output-dir.txt"
def MDG_JAVA_DEPENDENCIES = "mdg-java-dependencies.txt"
def METADATA_OUT_PATH = "$projectDir/src/main/assets/metadata"
// paths to jar libraries
def pluginsJarLibraries = new LinkedList<String>()
def allJarLibraries = new LinkedList<String>()
def computeCompileSdkVersion = { -> project.hasProperty("compileSdk") ? compileSdk : 28 }
def computeTargetSdkVersion = { -> project.hasProperty("targetSdk") ? targetSdk : 28 }
def computeBuildToolsVersion = { ->
project.hasProperty("buildToolsVersion") ? buildToolsVersion : "28.0.3"
}
project.ext.selectedBuildType = project.hasProperty("release") ? "release" : "debug"
buildscript {
// we have moved these initializations here as we need getAppResourcesPath to search for buildscript.gradle files,
// but the buildscript is executed before executing anything else from the gradle file
def initialize = { ->
// the build script will not work with previous versions of the CLI (3.1 or earlier)
def dependenciesJson = file("$rootDir/dependencies.json")
if (!dependenciesJson.exists()) {
throw new BuildCancelledException("""
'dependencies.json' file not found. Check whether the NativeScript CLI has prepared the project beforehand,
and that your NativeScript version is 3.3, or a more recent one. To build an android project with the current
version of the {N} CLI install a previous version of the runtime package - 'tns platform add android@3.2'.
""")
}
project.ext.extractedDependenciesDir = "${project.buildDir}/exploded-dependencies"
project.ext.cleanupAllJarsTimestamp = "${project.buildDir}/cleanupAllJars.timestamp"
project.ext.extractAllJarsTimestamp = "${project.buildDir}/extractAllJars.timestamp"
project.ext.nativescriptDependencies = new JsonSlurper().parseText(dependenciesJson.text)
project.ext.PLATFORMS_ANDROID = "platforms/android"
project.ext.USER_PROJECT_ROOT = "$rootDir/../.."
project.ext.getAppResourcesPath = { ->
def relativePathToApp = "app"
def relativePathToAppResources
def absolutePathToAppResources
def nsConfigFile = file("$USER_PROJECT_ROOT/nsconfig.json")
def nsConfig
if (nsConfigFile.exists()) {
nsConfig = new JsonSlurper().parseText(nsConfigFile.getText("UTF-8"))
}
if (nsConfig != null && nsConfig.appPath != null) {
relativePathToApp = nsConfig.appPath
}
if (nsConfig != null && nsConfig.appResourcesPath != null) {
relativePathToAppResources = nsConfig.appResourcesPath
} else {
relativePathToAppResources = "$relativePathToApp/App_Resources"
}
absolutePathToAppResources = java.nio.file.Paths.get(USER_PROJECT_ROOT).resolve(relativePathToAppResources).toAbsolutePath()
project.ext.appResourcesPath = absolutePathToAppResources
return absolutePathToAppResources
}
}
def applyBuildScriptConfigurations = { ->
def absolutePathToAppResources = getAppResourcesPath()
def pathToBuildScriptGradle = "$absolutePathToAppResources/Android/buildscript.gradle"
def buildScriptGradle = file(pathToBuildScriptGradle)
if (buildScriptGradle.exists()) {
println "\t + applying user-defined buildscript from ${buildScriptGradle}"
apply from: pathToBuildScriptGradle, to: buildscript
}
nativescriptDependencies.each { dep ->
def pathToPluginBuildScriptGradle = "$rootDir/${dep.directory}/$PLATFORMS_ANDROID/buildscript.gradle"
def pluginBuildScriptGradle = file(pathToPluginBuildScriptGradle)
if (pluginBuildScriptGradle.exists()) {
println "\t + applying user-defined buildscript from dependency ${pluginBuildScriptGradle}"
apply from: pathToPluginBuildScriptGradle, to: buildscript
}
}
}
initialize()
applyBuildScriptConfigurations()
}
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// CONFIGURATIONS ///////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
def applyBeforePluginGradleConfiguration = { ->
def appResourcesPath = getAppResourcesPath()
def pathToBeforePluginGradle = "$appResourcesPath/Android/before-plugins.gradle"
def beforePluginGradle = file(pathToBeforePluginGradle)
if (beforePluginGradle.exists()) {
println "\t + applying user-defined configuration from ${beforePluginGradle}"
apply from: pathToBeforePluginGradle
}
}
def applyAppGradleConfiguration = { ->
def appResourcesPath = getAppResourcesPath()
def pathToAppGradle = "$appResourcesPath/Android/app.gradle"
def appGradle = file(pathToAppGradle)
if (appGradle.exists()) {
println "\t + applying user-defined configuration from ${appGradle}"
apply from: pathToAppGradle
} else {
println "\t + couldn't load user-defined configuration from ${appGradle}. File doesn't exist."
}
}
def applyPluginGradleConfigurations = { ->
nativescriptDependencies.each { dep ->
def includeGradlePath = "$rootDir/${dep.directory}/$PLATFORMS_ANDROID/include.gradle"
if (file(includeGradlePath).exists()) {
apply from: includeGradlePath
}
}
}
def getAppIdentifier = { packageJsonMap ->
def appIdentifier = ""
if (packageJsonMap && packageJsonMap.nativescript) {
appIdentifier = packageJsonMap.nativescript.id
if (!(appIdentifier instanceof String)) {
appIdentifier = appIdentifier.android
}
}
return appIdentifier
}
def setAppIdentifier = { ->
println "\t + setting applicationId"
File packageJsonFile = new File("$rootDir/../../package.json")
if (packageJsonFile.exists()) {
def content = packageJsonFile.getText("UTF-8")
def jsonSlurper = new JsonSlurper()
def packageJsonMap = jsonSlurper.parseText(content)
def appIdentifier = getAppIdentifier(packageJsonMap)
if (appIdentifier) {
project.ext.nsApplicationIdentifier = appIdentifier
android.defaultConfig.applicationId = appIdentifier
}
}
}
android {
compileSdkVersion computeCompileSdkVersion()
buildToolsVersion computeBuildToolsVersion()
defaultConfig {
def manifest = new XmlSlurper().parse(file(android.sourceSets.main.manifest.srcFile))
def minSdkVer = manifest."uses-sdk"."@android:minSdkVersion".text() ?: 17
minSdkVersion minSdkVer
targetSdkVersion computeTargetSdkVersion()
ndk {
if (onlyX86) {
abiFilters 'x86'
} else {
abiFilters 'x86', 'armeabi-v7a', 'arm64-v8a'
}
}
dexOptions {
jumboMode = true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets.main {
jniLibs.srcDir "$projectDir/libs/jni"
}
signingConfigs {
release {
if (project.hasProperty("release")) {
if (project.hasProperty("ksPath") &&
project.hasProperty("ksPassword") &&
project.hasProperty("alias") &&
project.hasProperty("password")) {
storeFile file(ksPath)
storePassword ksPassword
keyAlias alias
keyPassword password
}
}
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
setAppIdentifier()
applyBeforePluginGradleConfiguration()
applyPluginGradleConfigurations()
applyAppGradleConfiguration()
}
def externalRuntimeExists = !findProject(':runtime').is(null)
def pluginDependencies
repositories {
// used for local *.AAR files
pluginDependencies = nativescriptDependencies.collect {
"$rootDir/${it.directory}/$PLATFORMS_ANDROID"
}
// some plugins may have their android dependencies in a /libs subdirectory
pluginDependencies.addAll(nativescriptDependencies.collect {
"$rootDir/${it.directory}/$PLATFORMS_ANDROID/libs"
})
if (!externalRuntimeExists) {
pluginDependencies.add("libs/runtime-libs")
}
def appResourcesPath = getAppResourcesPath()
def localAppResourcesLibraries = "$appResourcesPath/Android/libs"
pluginDependencies.add(localAppResourcesLibraries)
if (pluginDependencies.size() > 0) {
flatDir {
dirs pluginDependencies
}
}
}
dependencies {
def supportVer = "28.0.0"
if (project.hasProperty("supportVersion")) {
supportVer = supportVersion
}
if (project.hasProperty("useAndroidX") && (useAndroidX || useAndroidX.toBoolean())) {
def androidXLegacyVersion = "1.0.0"
if (project.hasProperty("androidXLegacy")) {
androidXLegacyVersion = androidXLegacy
}
def androidXAppCompatVersion = "1.1.0-alpha01"
if (project.hasProperty("androidXAppCompat")) {
androidXAppCompatVersion = androidXAppCompat
}
def androidXMaterialVersion = "1.1.0-alpha01"
if (project.hasProperty("androidXMaterial")) {
androidXMaterialVersion = androidXMaterial
}
println "\t + using andorid X library androidx.legacy:legacy-support-v4:$androidXLegacyVersion"
implementation "androidx.multidex:multidex:2.0.0"
implementation "androidx.legacy:legacy-support-v4:$androidXLegacyVersion"
implementation "androidx.appcompat:appcompat:$androidXAppCompatVersion"
implementation "com.google.android.material:material:$androidXMaterialVersion"
} else {
println "\t + using support library version $supportVer"
implementation "com.android.support:multidex:1.0.2"
implementation "com.android.support:support-v4:$supportVer"
implementation "com.android.support:appcompat-v7:$supportVer"
implementation "com.android.support:design:$supportVer"
}
def useV8Symbols = nativescriptDependencies.any {
def packageJsonPath = file("$rootDir/${it.directory}/$PACKAGE_JSON")
def packageJson = new JsonSlurper().parseText(packageJsonPath.text)
return packageJson.nativescript.useV8Symbols
}
if (!externalRuntimeExists) {
def runtime = "nativescript-optimized-with-inspector"
if (project.gradle.startParameter.taskNames.any { it.toLowerCase().contains('release') }) {
runtime = "nativescript-optimized"
}
if (useV8Symbols) {
runtime = "nativescript-regular"
}
println "\t + adding nativescript runtime package dependency: $runtime"
project.dependencies.add("implementation", [name: runtime, ext: "aar"])
} else {
implementation project(':runtime')
}
}
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// CONFIGURATION PHASE //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
task addDependenciesFromNativeScriptPlugins {
nativescriptDependencies.each { dep ->
def aarFiles = fileTree(dir: file("$rootDir/${dep.directory}/$PLATFORMS_ANDROID"), include: ["**/*.aar"])
aarFiles.each { aarFile ->
def length = aarFile.name.length() - 4
def fileName = aarFile.name[0..<length]
println "\t + adding aar plugin dependency: " + aarFile.getAbsolutePath()
project.dependencies.add("implementation", [name: fileName, ext: "aar"])
}
def jarFiles = fileTree(dir: file("$rootDir/${dep.directory}/$PLATFORMS_ANDROID"), include: ["**/*.jar"])
jarFiles.each { jarFile ->
def jarFileAbsolutePath = jarFile.getAbsolutePath()
println "\t + adding jar plugin dependency: $jarFileAbsolutePath"
pluginsJarLibraries.add(jarFile.getAbsolutePath())
}
project.dependencies.add("implementation", jarFiles)
}
}
task addDependenciesFromAppResourcesLibraries {
def appResourcesPath = getAppResourcesPath()
def appResourcesLibraries = file("$appResourcesPath/Android/libs")
if (appResourcesLibraries.exists()) {
def aarFiles = fileTree(dir: appResourcesLibraries, include: ["**/*.aar"])
aarFiles.each { aarFile ->
def length = aarFile.name.length() - 4
def fileName = aarFile.name[0..<length]
println "\t + adding aar library dependency: " + aarFile.getAbsolutePath()
project.dependencies.add("implementation", [name: fileName, ext: "aar"])
}
def jarFiles = fileTree(dir: appResourcesLibraries, include: ["**/*.jar"])
jarFiles.each { jarFile ->
def jarFileAbsolutePath = jarFile.getAbsolutePath()
println "\t + adding jar plugin dependency: $jarFileAbsolutePath"
pluginsJarLibraries.add(jarFile.getAbsolutePath())
}
project.dependencies.add("implementation", jarFiles)
}
}
tasks.whenTaskAdded({ org.gradle.api.DefaultTask currentTask ->
if (currentTask =~ /generate.+BuildConfig/) {
currentTask.finalizedBy(extractAllJars)
extractAllJars.finalizedBy(collectAllJars)
}
if (currentTask =~ /compile.+JavaWithJavac/) {
currentTask.dependsOn(makeAndroidXChanges)
currentTask.dependsOn(runSbg)
currentTask.finalizedBy(ensureMetadataOutDir)
ensureMetadataOutDir.finalizedBy(buildMetadata)
}
if (currentTask =~ /merge.*Assets/) {
currentTask.shouldRunAfter(buildMetadata)
}
if (currentTask =~ /assemble.*Debug/ || currentTask =~ /assemble.*Release/) {
currentTask.finalizedBy("validateAppIdMatch")
}
})
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// EXECUTUION PHASE /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
task runSbg(type: JavaExec) {
dependsOn "collectAllJars"
if (!findProject(':static-binding-generator').is(null)) {
dependsOn ':static-binding-generator:jar'
}
outputs.dir("$OUTPUT_JAVA_DIR/com/tns/gen")
inputs.dir(INPUT_JS_DIR)
inputs.dir(extractedDependenciesDir)
workingDir "$BUILD_TOOLS_PATH"
main "-jar"
args "static-binding-generator.jar"
doFirst {
new File("$OUTPUT_JAVA_DIR/com/tns/gen").deleteDir()
}
}
task ensureMetadataOutDir {
doLast {
def outputDir = file("$METADATA_OUT_PATH")
outputDir.mkdirs()
}
}
def explodeAar(File compileDependency, File outputDir) {
logger.info("explodeAar: Extracting ${compileDependency.path} -> ${outputDir.path}")
if (compileDependency.name.endsWith(".aar")) {
java.util.jar.JarFile jar = new java.util.jar.JarFile(compileDependency)
Enumeration enumEntries = jar.entries()
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement()
if (file.name.endsWith(".jar")) {
def targetFile = new File(outputDir, file.name)
InputStream inputStream = jar.getInputStream(file)
new File(targetFile.parent).mkdirs()
Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
if (file.isDirectory()) {
continue
}
}
jar.close()
} else if (compileDependency.name.endsWith(".jar")) {
copy {
from compileDependency.absolutePath
into outputDir
}
}
}
def md5(String string) {
MessageDigest digest = MessageDigest.getInstance("MD5") ;
digest.update(string.bytes);
return new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0');
}
class WorkerTask extends DefaultTask {
@Inject
WorkerExecutor getWorkerExecutor() {
throw new UnsupportedOperationException()
}
}
class EmptyRunnable implements Runnable {
void run() {
}
}
// Discover all jars and dynamically create tasks for the extraction of each of them
def allJars = []
afterEvaluate { project ->
def buildType = project.selectedBuildType == "release" ? "Release" : "Debug"
def jars = []
Pattern pattern = Pattern.compile("^(.+)${buildType}CompileClasspath\$")
def artifactType = Attribute.of('artifactType', String)
configurations.all { config ->
Matcher matcher = pattern.matcher(config.name)
if (matcher.find() || config.name == "${buildType.toLowerCase()}CompileClasspath") {
config.incoming.artifactView {
attributes {
it.attribute(artifactType, 'jar')
}
}.artifacts.each {
def jar = it.file;
if (!jars.contains(jar)) {
jars.push(jar)
def destDir = md5(jar.path);
def outputDir = new File(Paths.get(extractedDependenciesDir, destDir).normalize().toString())
def taskName = "extract_${jar.name}_to_${destDir}"
logger.debug("Creating dynamic task ${taskName}")
// Add discovered jars as dependencies of cleanupAllJars.
// This is cruicial for cloud builds because they are different
// on each incremental build (as each time the gradle user home
// directory is a randomly generated string)
cleanupAllJars.inputs.files jar
task "${taskName}" (type: WorkerTask) {
dependsOn cleanupAllJars
extractAllJars.dependsOn it
// This dependency seems redundant but probably due to some Gradle issue with workers,
// without it `runSbg` sporadically starts before all extraction tasks have finished and
// fails due to missing JARs
runSbg.dependsOn it
inputs.files jar
outputs.dir outputDir
doLast {
// Runing in parallel no longer seems to bring any benefit.
// It mattered only when we were extracting JARs from AARs.
// To try it simply remove the following comments.
// workerExecutor.submit(EmptyRunnable.class) {
explodeAar(jar, outputDir)
// }
}
}
allJars.push([file: jar, outputDir: outputDir])
}
}
}
}
}
task cleanupAllJars {
// We depend on the list of libs directories that might contain aar or jar files
// and on the list of all discovered jars
inputs.files(pluginDependencies)
outputs.files cleanupAllJarsTimestamp
doLast {
def allDests = allJars*.outputDir*.name;
def dir = new File(extractedDependenciesDir)
if (dir.exists()) {
dir.eachDir {
// An old directory which is no longer a dependency (e.g. orphaned by a deleted plugin)
if (!allDests.contains(it.name)) {
logger.info("Task cleanupAllJars: Deleting orphaned ${it.path}")
org.apache.commons.io.FileUtils.deleteDirectory(it)
}
}
}
new File(cleanupAllJarsTimestamp).write ""
}
}
// Placeholder task which depends on all dynamically generated extraction tasks
task extractAllJars {
dependsOn cleanupAllJars
outputs.files extractAllJarsTimestamp
doLast {
new File(cleanupAllJarsTimestamp).write ""
}
}
task collectAllJars {
dependsOn extractAllJars
description "gathers all paths to jar dependencies before building metadata with them"
def sdkPath = android.sdkDirectory.getAbsolutePath()
def androidJar = sdkPath + "/platforms/" + android.compileSdkVersion + "/android.jar"
doFirst {
def allJarPaths = new LinkedList<String>()
allJarPaths.add(androidJar)
allJarPaths.addAll(pluginsJarLibraries)
def ft = fileTree(dir: extractedDependenciesDir, include: "**/*.jar")
ft.each { currentJarFile ->
allJarPaths.add(currentJarFile.getAbsolutePath())
}
new File("$BUILD_TOOLS_PATH/$SBG_JAVA_DEPENDENCIES").withWriter { out ->
allJarPaths.each { out.println it }
}
new File("$BUILD_TOOLS_PATH/$MDG_JAVA_DEPENDENCIES").withWriter { out ->
allJarPaths.each {
if (it.endsWith(".jar")) {
out.println it
}
}
}
new File("$BUILD_TOOLS_PATH/$SBG_INPUT_FILE").withWriter { out ->
out.println INPUT_JS_DIR
}
new File("$BUILD_TOOLS_PATH/$SBG_OUTPUT_FILE").withWriter { out ->
out.println OUTPUT_JAVA_DIR
}
allJarLibraries.addAll(allJarPaths)
}
}
task buildMetadata(type: JavaExec) {
if (!findProject(':android-metadata-generator').is(null)) {
dependsOn ':android-metadata-generator:jar'
}
description "builds metadata with provided jar dependencies"
inputs.files("$MDG_JAVA_DEPENDENCIES")
def classesDir = "$buildDir/intermediates/javac"
inputs.dir(classesDir)
outputs.files("$METADATA_OUT_PATH/treeNodeStream.dat", "$METADATA_OUT_PATH/treeStringsStream.dat", "$METADATA_OUT_PATH/treeValueStream.dat")
doFirst {
// get compiled classes to pass to metadata generator
// these need to be called after the classes have compiled
assert file(classesDir).exists()
def classesSubDirs = new File(classesDir).listFiles()
def selectedBuildType = project.ext.selectedBuildType
def generatedClasses = new LinkedList<String>()
for (File subDir : classesSubDirs) {
if (subDir.getName().equals(selectedBuildType)) {
generatedClasses.add(subDir.getAbsolutePath())
}
}
new File("$BUILD_TOOLS_PATH/$MDG_OUTPUT_DIR").withWriter { out ->
out.println "$METADATA_OUT_PATH"
}
new File("$BUILD_TOOLS_PATH/$MDG_JAVA_DEPENDENCIES").withWriterAppend { out ->
generatedClasses.each { out.println it }
}
workingDir "$BUILD_TOOLS_PATH"
main "-jar"
args "android-metadata-generator.jar"
}
}
task makeAndroidXChanges {
if (project.hasProperty("useAndroidX") && (useAndroidX || useAndroidX.toBoolean())) {
// code changes
def codeTuples = new ArrayList<Tuple2<String, String>>()
codeTuples.add(new Tuple2<String, String>('android\\.support\\.annotation\\.NonNull', 'androidx.annotation.NonNull'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v7\\.app\\.AppCompatActivity', 'androidx.appcompat.app.AppCompatActivity'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v7\\.appcompat\\.R', 'androidx.appcompat.R'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.design\\.widget\\.TabLayout', 'com.google.android.material.tabs.TabLayout'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v4\\.app\\.ActivityCompat', 'androidx.core.app.ActivityCompat'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v4\\.app\\.Fragment', 'androidx.fragment.app.Fragment'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v4\\.view\\.ViewPager', 'androidx.viewpager.widget.ViewPager'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.v7\\.widget\\.Toolbar', 'androidx.appcompat.widget.Toolbar'))
codeTuples.add(new Tuple2<String, String>('android\\.support\\.multidex\\.MultiDex', 'androidx.multidex.MultiDex'))
codeTuples.each { tuple ->
ant.replaceregexp(match: tuple.first, replace: tuple.second, flags: 'g', byline: true) {
fileset(dir: "$projectDir/src/debug/java/com/tns/", includes: '*.java')
}
ant.replaceregexp(match: tuple.first, replace: tuple.second, flags: 'g', byline: true) {
fileset(dir: "$projectDir/src/main/java/com/tns/", includes: '*.java')
}
}
// resource changes
def resourceTuples = new ArrayList<Tuple2<String, String>>()
resourceTuples.add(new Tuple2<String, String>('android\\.support\\.v7\\.widget\\.Toolbar', 'androidx.appcompat.widget.Toolbar'))
resourceTuples.add(new Tuple2<String, String>('android\\.support\\.v4\\.view\\.ViewPager', 'androidx.viewpager.widget.ViewPager'))
resourceTuples.add(new Tuple2<String, String>('android\\.support\\.design\\.widget\\.TabLayout', 'com.google.android.material.tabs.TabLayout'))
resourceTuples.each { tuple ->
ant.replaceregexp(match: tuple.first, replace: tuple.second, flags: 'g', byline: true) {
fileset(dir: "$projectDir/src/debug/res/layout/", includes: 'error_activity.xml')
}
}
}
}
task generateTypescriptDefinitions(type: JavaExec) {
if (!findProject(':dts-generator').is(null)) {
dependsOn ':dts-generator:jar'
}
def paramz = new ArrayList<String>()
def includeDirs = ["com.android.support", "/platforms/" + android.compileSdkVersion]
doFirst {
delete "$TYPINGS_PATH"
workingDir "$BUILD_TOOLS_PATH"
main "-jar"
paramz.add("dts-generator.jar")
paramz.add("-input")
for (String jarPath : allJarLibraries) {
// don't generate typings for runtime jars and classes
if (shouldIncludeDirForTypings(jarPath, includeDirs)) {
paramz.add(jarPath)
}
}
paramz.add("-output")
paramz.add("$TYPINGS_PATH")
new File("$TYPINGS_PATH").mkdirs()
logger.info("Task generateTypescriptDefinitions: Call dts-generator.jar with arguments: " + paramz.toString().replaceAll(',', ''))
println "Task generateTypescriptDefinitions: Call dts-generator.jar with arguments: " + paramz.toString().replaceAll(',', '')
args paramz.toArray()
}
}
generateTypescriptDefinitions.onlyIf {
(project.hasProperty("generateTypings") && Boolean.parseBoolean(project.generateTypings)) || PASSED_TYPINGS_PATH != null
}
collectAllJars.finalizedBy(generateTypescriptDefinitions)
static def shouldIncludeDirForTypings(path, includeDirs) {
for (String p : includeDirs) {
if (path.indexOf(p) > -1) {
return true
}
}
return false
}
task copyTypings {
doLast {
println "Copied generated typings to application root level. Make sure to import android.d.ts in reference.d.ts"
copy {
from "$TYPINGS_PATH"
into "$USER_PROJECT_ROOT"
}
}
}
copyTypings.onlyIf { generateTypescriptDefinitions.didWork }
generateTypescriptDefinitions.finalizedBy(copyTypings)
task validateAppIdMatch {
doLast {
def lineSeparator = System.getProperty("line.separator")
if (project.hasProperty("nsApplicationIdentifier") && !project.hasProperty("release")) {
if (project.nsApplicationIdentifier != android.defaultConfig.applicationId) {
def errorMessage = "${lineSeparator}WARNING: The Application identifier is different from the one inside \"package.json\" file.$lineSeparator" +
"NativeScript CLI might not work properly.$lineSeparator" +
"Remove applicationId from app.gradle and update the \"nativescript.id\" in package.json.$lineSeparator" +
"Actual: ${android.defaultConfig.applicationId}$lineSeparator" +
"Expected(from \"package.json\"): ${project.nsApplicationIdentifier}$lineSeparator"
logger.error(errorMessage)
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// OPTIONAL TASKS //////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
//////// custom clean ///////////
task cleanSbg(type: Delete) {
delete "$BUILD_TOOLS_PATH/$SBG_JS_PARSED_FILES",
"$BUILD_TOOLS_PATH/$SBG_JAVA_DEPENDENCIES",
"$BUILD_TOOLS_PATH/$SBG_INTERFACE_NAMES",
"$BUILD_TOOLS_PATH/$SBG_BINDINGS_NAME",
"$BUILD_TOOLS_PATH/$SBG_INPUT_FILE",
"$BUILD_TOOLS_PATH/$SBG_OUTPUT_FILE",
"$OUTPUT_JAVA_DIR/com/tns/gen"
}
task cleanMdg(type: Delete) {
delete "$BUILD_TOOLS_PATH/$MDG_OUTPUT_DIR",
"$BUILD_TOOLS_PATH/$MDG_JAVA_DEPENDENCIES",
"$METADATA_OUT_PATH"
}
cleanSbg.dependsOn(cleanMdg)
clean.dependsOn(cleanSbg)