forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroid-project-service.ts
988 lines (891 loc) · 28.7 KB
/
android-project-service.ts
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
import * as path from "path";
import * as shell from "shelljs";
import * as _ from "lodash";
import * as constants from "../constants";
import * as semver from "semver";
import * as projectServiceBaseLib from "./platform-project-service-base";
import { DeviceAndroidDebugBridge } from "../common/mobile/android/device-android-debug-bridge";
import { Configurations, LiveSyncPaths } from "../common/constants";
import { hook } from "../common/helpers";
import { performanceLog } from ".././common/decorators";
import {
IProjectData,
IProjectDataService,
IValidatePlatformOutput,
} from "../definitions/project";
import {
IPlatformData,
IBuildOutputOptions,
IPlatformEnvironmentRequirements,
IValidBuildOutputData,
} from "../definitions/platform";
import {
IAndroidToolsInfo,
IAndroidResourcesMigrationService,
IOptions,
IDependencyData,
} from "../declarations";
import { IAndroidBuildData } from "../definitions/build";
import { IPluginData } from "../definitions/plugins";
import {
IErrors,
IFileSystem,
IAnalyticsService,
IDictionary,
IRelease,
ISpawnResult,
} from "../common/declarations";
import {
IAndroidPluginBuildService,
IPluginBuildOptions,
} from "../definitions/android-plugin-migrator";
import { IFilesHashService } from "../definitions/files-hash-service";
import {
IGradleCommandService,
IGradleBuildService,
} from "../definitions/gradle";
import { IInjector } from "../common/definitions/yok";
import { injector } from "../common/yok";
import { INotConfiguredEnvOptions } from "../common/definitions/commands";
interface NativeDependency {
name: string;
directory: string;
dependencies: string[];
}
//
// we sort the native dependencies topologically to make sure they are processed in the right order
// native dependenciess need to be sorted so the deepst dependencies are built before it's parents
//
// for example, given this dep structure (assuming these are all native dependencies that need to be built)
// (note: we list all dependencies at the root level, so the leaf nodes are essentially references to the root nodes)
//
// |- dep1
// |- dep2
// |- |- dep3
// |- |- dep4
// |- |- |- dep5
// |- dep3
// |- dep4
// |- |- dep5
// |- dep5
//
// It is sorted:
//
// |- dep1
// |- dep3
// |- dep5
// |- dep4 # depends on dep5, so dep5 must be built first, ie above ^
// |- |- dep5
// |- dep2 # depends on dep3, dep4 (and dep5 through dep4) so all of them must be built first before dep2 is built
// |- |- dep3
// |- |- dep4
// |- |- |- dep5
//
// for more details see: https://wikiless.org/wiki/Topological_sorting?lang=en
//
function topologicalSortNativeDependencies(
dependencies: NativeDependency[],
start: NativeDependency[] = [],
depth = 0,
total = 0 // do not pass in, we calculate it in the initial run!
): NativeDependency[] {
// we set the total on the initial call - and never increment it, as it's used for esacaping the recursion
if (total === 0) {
total = dependencies.length;
}
const sortedDeps = dependencies.reduce(
(sortedDeps, currentDependency: NativeDependency) => {
const allSubDependenciesProcessed = currentDependency.dependencies.every(
(subDependency) => {
return sortedDeps.some((dep) => dep.name === subDependency);
}
);
if (allSubDependenciesProcessed) {
sortedDeps.push(currentDependency);
}
return sortedDeps;
},
start
);
const remainingDeps = dependencies.filter(
(nativeDep) => !sortedDeps.includes(nativeDep)
);
// recurse if we still have remaining deps
// the second condition here prevents infinite recursion
if (remainingDeps.length && sortedDeps.length < total) {
return topologicalSortNativeDependencies(
remainingDeps,
sortedDeps,
depth + 1,
total
);
}
return sortedDeps;
}
export class AndroidProjectService extends projectServiceBaseLib.PlatformProjectServiceBase {
private static VALUES_DIRNAME = "values";
private static VALUES_VERSION_DIRNAME_PREFIX =
AndroidProjectService.VALUES_DIRNAME + "-v";
private static ANDROID_PLATFORM_NAME = "android";
private static MIN_RUNTIME_VERSION_WITH_GRADLE = "1.5.0";
constructor(
private $androidToolsInfo: IAndroidToolsInfo,
private $errors: IErrors,
$fs: IFileSystem,
private $logger: ILogger,
$projectDataService: IProjectDataService,
private $options: IOptions,
private $injector: IInjector,
private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants,
private $androidPluginBuildService: IAndroidPluginBuildService,
private $platformEnvironmentRequirements: IPlatformEnvironmentRequirements,
private $androidResourcesMigrationService: IAndroidResourcesMigrationService,
private $filesHashService: IFilesHashService,
private $gradleCommandService: IGradleCommandService,
private $gradleBuildService: IGradleBuildService,
private $analyticsService: IAnalyticsService
) {
super($fs, $projectDataService);
}
private _platformData: IPlatformData = null;
public getPlatformData(projectData: IProjectData): IPlatformData {
if (!projectData && !this._platformData) {
throw new Error(
"First call of getPlatformData without providing projectData."
);
}
if (projectData && projectData.platformsDir) {
const projectRoot = path.join(
projectData.platformsDir,
AndroidProjectService.ANDROID_PLATFORM_NAME
);
const appDestinationDirectoryArr = [
projectRoot,
constants.APP_FOLDER_NAME,
constants.SRC_DIR,
constants.MAIN_DIR,
constants.ASSETS_DIR,
];
const configurationsDirectoryArr = [
projectRoot,
constants.APP_FOLDER_NAME,
constants.SRC_DIR,
constants.MAIN_DIR,
constants.MANIFEST_FILE_NAME,
];
const deviceBuildOutputArr = [
projectRoot,
constants.APP_FOLDER_NAME,
constants.BUILD_DIR,
constants.OUTPUTS_DIR,
constants.APK_DIR,
];
const packageName = this.getProjectNameFromId(projectData);
const runtimePackage = this.$projectDataService.getRuntimePackage(
projectData.projectDir,
constants.PlatformTypes.android
);
this._platformData = {
frameworkPackageName: runtimePackage.name,
normalizedPlatformName: "Android",
platformNameLowerCase: "android",
appDestinationDirectoryPath: path.join(...appDestinationDirectoryArr),
platformProjectService: <any>this,
projectRoot: projectRoot,
getBuildOutputPath: (buildOptions: IBuildOutputOptions) => {
if (buildOptions.androidBundle) {
return path.join(
projectRoot,
constants.APP_FOLDER_NAME,
constants.BUILD_DIR,
constants.OUTPUTS_DIR,
constants.BUNDLE_DIR
);
}
return path.join(...deviceBuildOutputArr);
},
getValidBuildOutputData: (
buildOptions: IBuildOutputOptions
): IValidBuildOutputData => {
const buildMode = buildOptions.release
? Configurations.Release.toLowerCase()
: Configurations.Debug.toLowerCase();
if (buildOptions.androidBundle) {
return {
packageNames: [
`${constants.APP_FOLDER_NAME}${constants.AAB_EXTENSION_NAME}`,
`${constants.APP_FOLDER_NAME}-${buildMode}${constants.AAB_EXTENSION_NAME}`,
],
};
}
return {
packageNames: [
`${packageName}-${buildMode}${constants.APK_EXTENSION_NAME}`,
`${projectData.projectName}-${buildMode}${constants.APK_EXTENSION_NAME}`,
`${projectData.projectName}${constants.APK_EXTENSION_NAME}`,
`${constants.APP_FOLDER_NAME}-${buildMode}${constants.APK_EXTENSION_NAME}`,
],
regexes: [
new RegExp(
`(${packageName}|${constants.APP_FOLDER_NAME})-.*-(${Configurations.Debug}|${Configurations.Release})(-unsigned)?${constants.APK_EXTENSION_NAME}`,
"i"
),
],
};
},
configurationFileName: constants.MANIFEST_FILE_NAME,
configurationFilePath: path.join(...configurationsDirectoryArr),
relativeToFrameworkConfigurationFilePath: path.join(
constants.SRC_DIR,
constants.MAIN_DIR,
constants.MANIFEST_FILE_NAME
),
fastLivesyncFileExtensions: [".jpg", ".gif", ".png", ".bmp", ".webp"], // http://developer.android.com/guide/appendix/media-formats.html
};
}
return this._platformData;
}
public getCurrentPlatformVersion(
platformData: IPlatformData,
projectData: IProjectData
): string {
const currentPlatformData: IDictionary<any> = this.$projectDataService.getRuntimePackage(
projectData.projectDir,
<constants.PlatformTypes>platformData.platformNameLowerCase
);
return currentPlatformData && currentPlatformData[constants.VERSION_STRING];
}
public async validateOptions(): Promise<boolean> {
return true;
}
public getAppResourcesDestinationDirectoryPath(
projectData: IProjectData
): string {
const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated(
projectData.getAppResourcesDirectoryPath()
);
if (appResourcesDirStructureHasMigrated) {
return this.getUpdatedAppResourcesDestinationDirPath(projectData);
} else {
return this.getLegacyAppResourcesDestinationDirPath(projectData);
}
}
public async validate(
projectData: IProjectData,
options: IOptions,
notConfiguredEnvOptions?: INotConfiguredEnvOptions
): Promise<IValidatePlatformOutput> {
this.validatePackageName(projectData.projectIdentifiers.android);
this.validateProjectName(projectData.projectName);
const checkEnvironmentRequirementsOutput = await this.$platformEnvironmentRequirements.checkEnvironmentRequirements(
{
platform: this.getPlatformData(projectData).normalizedPlatformName,
projectDir: projectData.projectDir,
options,
notConfiguredEnvOptions,
}
);
this.$androidToolsInfo.validateInfo({
showWarningsAsErrors: true,
projectDir: projectData.projectDir,
validateTargetSdk: true,
});
return {
checkEnvironmentRequirementsOutput,
};
}
public async createProject(
frameworkDir: string,
frameworkVersion: string,
projectData: IProjectData
): Promise<void> {
if (
semver.lt(
frameworkVersion,
AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE
)
) {
this.$errors.fail(
`The NativeScript CLI requires Android runtime ${AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE} or later to work properly.`
);
}
this.$fs.ensureDirectoryExists(
this.getPlatformData(projectData).projectRoot
);
const androidToolsInfo = this.$androidToolsInfo.getToolsInfo({
projectDir: projectData.projectDir,
});
const targetSdkVersion =
androidToolsInfo && androidToolsInfo.targetSdkVersion;
this.$logger.trace(`Using Android SDK '${targetSdkVersion}'.`);
this.copy(
this.getPlatformData(projectData).projectRoot,
frameworkDir,
"*",
"-R"
);
// TODO: Check if we actually need this and if it should be targetSdk or compileSdk
this.cleanResValues(targetSdkVersion, projectData);
}
private getResDestinationDir(projectData: IProjectData): string {
const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated(
projectData.getAppResourcesDirectoryPath()
);
if (appResourcesDirStructureHasMigrated) {
const appResourcesDestinationPath = this.getUpdatedAppResourcesDestinationDirPath(
projectData
);
return path.join(
appResourcesDestinationPath,
constants.MAIN_DIR,
constants.RESOURCES_DIR
);
} else {
return this.getLegacyAppResourcesDestinationDirPath(projectData);
}
}
private cleanResValues(
targetSdkVersion: number,
projectData: IProjectData
): void {
const resDestinationDir = this.getResDestinationDir(projectData);
const directoriesInResFolder = this.$fs.readDirectory(resDestinationDir);
const directoriesToClean = directoriesInResFolder
.map((dir) => {
return {
dirName: dir,
sdkNum: parseInt(
dir.substr(
AndroidProjectService.VALUES_VERSION_DIRNAME_PREFIX.length
)
),
};
})
.filter(
(dir) =>
dir.dirName.match(
AndroidProjectService.VALUES_VERSION_DIRNAME_PREFIX
) &&
dir.sdkNum &&
(!targetSdkVersion || targetSdkVersion < dir.sdkNum)
)
.map((dir) => path.join(resDestinationDir, dir.dirName));
this.$logger.trace("Directories to clean:");
this.$logger.trace(directoriesToClean);
_.map(directoriesToClean, (dir) => this.$fs.deleteDirectory(dir));
}
public async interpolateData(projectData: IProjectData): Promise<void> {
// Interpolate the apilevel and package
this.interpolateConfigurationFile(projectData);
const appResourcesDirectoryPath = projectData.getAppResourcesDirectoryPath();
let stringsFilePath: string;
const appResourcesDestinationDirectoryPath = this.getAppResourcesDestinationDirectoryPath(
projectData
);
if (
this.$androidResourcesMigrationService.hasMigrated(
appResourcesDirectoryPath
)
) {
stringsFilePath = path.join(
appResourcesDestinationDirectoryPath,
constants.MAIN_DIR,
constants.RESOURCES_DIR,
"values",
"strings.xml"
);
} else {
stringsFilePath = path.join(
appResourcesDestinationDirectoryPath,
"values",
"strings.xml"
);
}
shell.sed("-i", /__NAME__/, projectData.projectName, stringsFilePath);
shell.sed(
"-i",
/__TITLE_ACTIVITY__/,
projectData.projectName,
stringsFilePath
);
const gradleSettingsFilePath = path.join(
this.getPlatformData(projectData).projectRoot,
"settings.gradle"
);
shell.sed(
"-i",
/__PROJECT_NAME__/,
this.getProjectNameFromId(projectData),
gradleSettingsFilePath
);
try {
// will replace applicationId in app/App_Resources/Android/app.gradle if it has not been edited by the user
const appGradleContent = this.$fs.readText(projectData.appGradlePath);
if (appGradleContent.indexOf(constants.PACKAGE_PLACEHOLDER_NAME) !== -1) {
//TODO: For compatibility with old templates. Once all templates are updated should delete.
shell.sed(
"-i",
new RegExp(constants.PACKAGE_PLACEHOLDER_NAME),
projectData.projectIdentifiers.android,
projectData.appGradlePath
);
}
} catch (e) {
this.$logger.trace(
`Templates updated and no need for replace in app.gradle.`
);
}
}
public interpolateConfigurationFile(projectData: IProjectData): void {
const manifestPath = this.getPlatformData(projectData)
.configurationFilePath;
shell.sed(
"-i",
/__PACKAGE__/,
projectData.projectIdentifiers.android,
manifestPath
);
}
private getProjectNameFromId(projectData: IProjectData): string {
let id: string;
if (
projectData &&
projectData.projectIdentifiers &&
projectData.projectIdentifiers.android
) {
const idParts = projectData.projectIdentifiers.android.split(".");
id = idParts[idParts.length - 1];
}
return id;
}
public afterCreateProject(projectRoot: string): void {
return null;
}
public async updatePlatform(
currentVersion: string,
newVersion: string,
canUpdate: boolean,
projectData: IProjectData,
addPlatform?: Function,
removePlatforms?: (platforms: string[]) => Promise<void>
): Promise<boolean> {
if (
semver.eq(
newVersion,
AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE
)
) {
const platformLowercase = this.getPlatformData(
projectData
).normalizedPlatformName.toLowerCase();
await removePlatforms([platformLowercase.split("@")[0]]);
await addPlatform(platformLowercase);
return false;
}
return true;
}
@performanceLog()
@hook("buildAndroid")
public async buildProject(
projectRoot: string,
projectData: IProjectData,
buildData: IAndroidBuildData
): Promise<void> {
const platformData = this.getPlatformData(projectData);
await this.$gradleBuildService.buildProject(
platformData.projectRoot,
buildData
);
const outputPath = platformData.getBuildOutputPath(buildData);
await this.$filesHashService.saveHashesForProject(
this._platformData,
outputPath
);
await this.trackKotlinUsage(projectRoot);
}
public async buildForDeploy(
projectRoot: string,
projectData: IProjectData,
buildData?: IAndroidBuildData
): Promise<void> {
return this.buildProject(projectRoot, projectData, buildData);
}
public isPlatformPrepared(
projectRoot: string,
projectData: IProjectData
): boolean {
return this.$fs.exists(
path.join(
this.getPlatformData(projectData).appDestinationDirectoryPath,
constants.APP_FOLDER_NAME
)
);
}
public getFrameworkFilesExtensions(): string[] {
return [".jar", ".dat"];
}
public async prepareProject(): Promise<void> {
// Intentionally left empty.
}
public ensureConfigurationFileInAppResources(
projectData: IProjectData
): void {
const appResourcesDirectoryPath = projectData.appResourcesDirectoryPath;
const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated(
appResourcesDirectoryPath
);
let originalAndroidManifestFilePath;
if (appResourcesDirStructureHasMigrated) {
originalAndroidManifestFilePath = path.join(
appResourcesDirectoryPath,
this.$devicePlatformsConstants.Android,
"src",
"main",
this.getPlatformData(projectData).configurationFileName
);
} else {
originalAndroidManifestFilePath = path.join(
appResourcesDirectoryPath,
this.$devicePlatformsConstants.Android,
this.getPlatformData(projectData).configurationFileName
);
}
const manifestExists = this.$fs.exists(originalAndroidManifestFilePath);
if (!manifestExists) {
this.$logger.warn(
"No manifest found in " + originalAndroidManifestFilePath
);
return;
}
// Overwrite the AndroidManifest from runtime.
if (!appResourcesDirStructureHasMigrated) {
this.$fs.copyFile(
originalAndroidManifestFilePath,
this.getPlatformData(projectData).configurationFilePath
);
}
}
public prepareAppResources(projectData: IProjectData): void {
const platformData = this.getPlatformData(projectData);
const projectAppResourcesPath = projectData.getAppResourcesDirectoryPath(
projectData.projectDir
);
const platformsAppResourcesPath = this.getAppResourcesDestinationDirectoryPath(
projectData
);
this.cleanUpPreparedResources(projectData);
this.$fs.ensureDirectoryExists(platformsAppResourcesPath);
const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated(
projectAppResourcesPath
);
if (appResourcesDirStructureHasMigrated) {
this.$fs.copyFile(
path.join(
projectAppResourcesPath,
platformData.normalizedPlatformName,
constants.SRC_DIR,
"*"
),
platformsAppResourcesPath
);
} else {
this.$fs.copyFile(
path.join(
projectAppResourcesPath,
platformData.normalizedPlatformName,
"*"
),
platformsAppResourcesPath
);
// https://github.com/NativeScript/android-runtime/issues/899
// App_Resources/Android/libs is reserved to user's aars and jars, but they should not be copied as resources
this.$fs.deleteDirectory(path.join(platformsAppResourcesPath, "libs"));
}
const androidToolsInfo = this.$androidToolsInfo.getToolsInfo({
projectDir: projectData.projectDir,
});
const compileSdkVersion =
androidToolsInfo && androidToolsInfo.compileSdkVersion;
this.cleanResValues(compileSdkVersion, projectData);
}
public async preparePluginNativeCode(
pluginData: IPluginData,
projectData: IProjectData
): Promise<void> {
// build Android plugins which contain AndroidManifest.xml and/or resources
const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath(
pluginData,
AndroidProjectService.ANDROID_PLATFORM_NAME
);
if (this.$fs.exists(pluginPlatformsFolderPath)) {
const options: IPluginBuildOptions = {
gradlePath: this.$options.gradlePath,
gradleArgs: this.$options.gradleArgs,
projectDir: projectData.projectDir,
pluginName: pluginData.name,
platformsAndroidDirPath: pluginPlatformsFolderPath,
aarOutputDir: pluginPlatformsFolderPath,
tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"),
};
if (await this.$androidPluginBuildService.buildAar(options)) {
this.$logger.info(`Built aar for ${options.pluginName}`);
}
this.$androidPluginBuildService.migrateIncludeGradle(options);
}
}
public async processConfigurationFilesFromAppResources(): Promise<void> {
return;
}
public async removePluginNativeCode(
pluginData: IPluginData,
projectData: IProjectData
): Promise<void> {
// not implemented
}
public async beforePrepareAllPlugins(
projectData: IProjectData,
dependencies?: IDependencyData[]
): Promise<IDependencyData[]> {
if (dependencies) {
dependencies = this.filterUniqueDependencies(dependencies);
return this.provideDependenciesJson(projectData, dependencies);
}
}
public async handleNativeDependenciesChange(
projectData: IProjectData,
opts: IRelease
): Promise<void> {
return;
}
private filterUniqueDependencies(
dependencies: IDependencyData[]
): IDependencyData[] {
const depsDictionary = dependencies.reduce((dict, dep) => {
const collision = dict[dep.name];
// in case there are multiple dependencies to the same module, the one declared in the package.json takes precedence
if (!collision || collision.depth > dep.depth) {
dict[dep.name] = dep;
}
return dict;
}, <IDictionary<IDependencyData>>{});
return _.values(depsDictionary);
}
private provideDependenciesJson(
projectData: IProjectData,
dependencies: IDependencyData[]
): IDependencyData[] {
const platformDir = path.join(
projectData.platformsDir,
AndroidProjectService.ANDROID_PLATFORM_NAME
);
const dependenciesJsonPath = path.join(
platformDir,
constants.DEPENDENCIES_JSON_NAME
);
let nativeDependencyData = dependencies.filter(
AndroidProjectService.isNativeAndroidDependency
);
let nativeDependencies = nativeDependencyData.map(
({ name, directory, dependencies }) => {
return {
name,
directory: path.relative(platformDir, directory),
dependencies: dependencies.filter((dep) => {
// filter out transient dependencies that don't have native dependencies
return (
nativeDependencyData.findIndex(
(nativeDep) => nativeDep.name === dep
) !== -1
);
}),
} as NativeDependency;
}
);
nativeDependencies = topologicalSortNativeDependencies(nativeDependencies);
const jsonContent = JSON.stringify(nativeDependencies, null, 4);
this.$fs.writeFile(dependenciesJsonPath, jsonContent);
// we sort all the dependencies to respect the topological sorting of the native dependencies
return dependencies.sort(function (a, b) {
return (
nativeDependencies.findIndex((n) => n.name === a.name) -
nativeDependencies.findIndex((n) => n.name === b.name)
);
});
}
private static isNativeAndroidDependency({
nativescript,
}: IDependencyData): boolean {
return (
nativescript &&
(nativescript.android ||
(nativescript.platforms && nativescript.platforms.android))
);
}
public async stopServices(projectRoot: string): Promise<ISpawnResult> {
const result = await this.$gradleCommandService.executeCommand(
["--stop", "--quiet"],
{
cwd: projectRoot,
message: "Gradle stop services...",
stdio: "pipe",
}
);
return result;
}
public async cleanProject(projectRoot: string): Promise<void> {
await this.$gradleBuildService.cleanProject(projectRoot, <any>{
release: false,
});
}
public async cleanDeviceTempFolder(
deviceIdentifier: string,
projectData: IProjectData
): Promise<void> {
const adb = this.$injector.resolve(DeviceAndroidDebugBridge, {
identifier: deviceIdentifier,
});
const deviceRootPath = `${LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${projectData.projectIdentifiers.android}`;
await adb.executeShellCommand(["rm", "-rf", deviceRootPath]);
}
public async checkForChanges(): Promise<void> {
// Nothing android specific to check yet.
}
public getDeploymentTarget(projectData: IProjectData): semver.SemVer {
return;
}
private copy(
projectRoot: string,
frameworkDir: string,
files: string,
cpArg: string
): void {
const paths = files.split(" ").map((p) => path.join(frameworkDir, p));
shell.cp(cpArg, paths, projectRoot);
}
private validatePackageName(packageName: string): void {
//Make the package conform to Java package types
//Enforce underscore limitation
if (!/^[a-zA-Z]+(\.[a-zA-Z0-9][a-zA-Z0-9_]*)+$/.test(packageName)) {
this.$errors.fail(
`Package name must look like: com.company.Name. Got: ${packageName}`
);
}
//Class is a reserved word
if (/\b[Cc]lass\b/.test(packageName)) {
this.$errors.fail("class is a reserved word");
}
}
private validateProjectName(projectName: string): void {
if (projectName === "") {
this.$errors.fail("Project name cannot be empty");
}
//Classes in Java don't begin with numbers
if (/^[0-9]/.test(projectName)) {
this.$errors.fail("Project name must not begin with a number");
}
}
private getLegacyAppResourcesDestinationDirPath(
projectData: IProjectData
): string {
const resourcePath: string[] = [
constants.APP_FOLDER_NAME,
constants.SRC_DIR,
constants.MAIN_DIR,
constants.RESOURCES_DIR,
];
return path.join(
this.getPlatformData(projectData).projectRoot,
...resourcePath
);
}
private getUpdatedAppResourcesDestinationDirPath(
projectData: IProjectData
): string {
const resourcePath: string[] = [
constants.APP_FOLDER_NAME,
constants.SRC_DIR,
];
return path.join(
this.getPlatformData(projectData).projectRoot,
...resourcePath
);
}
/**
* The purpose of this method is to delete the previously prepared user resources.
* The content of the `<platforms>/android/.../res` directory is based on user's resources and gradle project template from android-runtime.
* During preparation of the `<path to user's App_Resources>/Android` we want to clean all the users files from previous preparation,
* but keep the ones that were introduced during `platform add` of the android-runtime.
* Currently the Gradle project template contains resources only in values and values-v21 directories.
* So the current logic of the method is cleaning al resources from `<platforms>/android/.../res` that are not in `values.*` directories
* and that exist in the `<path to user's App_Resources>/Android/.../res` directory
* This means that if user has a resource file in values-v29 for example, builds the project and then deletes this resource,
* it will be kept in platforms directory. Reference issue: `https://github.com/NativeScript/nativescript-cli/issues/5083`
* Same is valid for files in `drawable-<resolution>` directories - in case in user's resources there's drawable-hdpi directory,
* which is deleted after the first build of app, it will remain in platforms directory.
*/
private cleanUpPreparedResources(projectData: IProjectData): void {
let resourcesDirPath = path.join(
projectData.appResourcesDirectoryPath,
this.getPlatformData(projectData).normalizedPlatformName
);
if (
this.$androidResourcesMigrationService.hasMigrated(
projectData.appResourcesDirectoryPath
)
) {
resourcesDirPath = path.join(
resourcesDirPath,
constants.SRC_DIR,
constants.MAIN_DIR,
constants.RESOURCES_DIR
);
}
const valuesDirRegExp = /^values/;
if (this.$fs.exists(resourcesDirPath)) {
const resourcesDirs = this.$fs
.readDirectory(resourcesDirPath)
.filter((resDir) => !resDir.match(valuesDirRegExp));
const resDestinationDir = this.getResDestinationDir(projectData);
_.each(resourcesDirs, (currentResource) => {
this.$fs.deleteDirectory(path.join(resDestinationDir, currentResource));
});
}
}
private async trackKotlinUsage(projectRoot: string): Promise<void> {
const buildStatistics = this.tryGetAndroidBuildStatistics(projectRoot);
try {
if (buildStatistics && buildStatistics.kotlinUsage) {
const analyticsDelimiter = constants.AnalyticsEventLabelDelimiter;
const hasUseKotlinPropertyInAppData = `hasUseKotlinPropertyInApp${analyticsDelimiter}${buildStatistics.kotlinUsage.hasUseKotlinPropertyInApp}`;
const hasKotlinRuntimeClassesData = `hasKotlinRuntimeClasses${analyticsDelimiter}${buildStatistics.kotlinUsage.hasKotlinRuntimeClasses}`;
await this.$analyticsService.trackEventActionInGoogleAnalytics({
action: constants.TrackActionNames.UsingKotlin,
additionalData: `${hasUseKotlinPropertyInAppData}${analyticsDelimiter}${hasKotlinRuntimeClassesData}`,
});
}
} catch (e) {
this.$logger.trace(
`Failed to track android build statistics. Error is: ${e.message}`
);
}
}
private tryGetAndroidBuildStatistics(projectRoot: string): any {
const staticsFilePath = path.join(
projectRoot,
constants.ANDROID_ANALYTICS_DATA_DIR,
constants.ANDROID_ANALYTICS_DATA_FILE
);
let buildStatistics;
if (this.$fs.exists(staticsFilePath)) {
try {
buildStatistics = this.$fs.readJson(staticsFilePath);
} catch (e) {
this.$logger.trace(
`Unable to read android build statistics file. Error is ${e.message}`
);
}
}
return buildStatistics;
}
}
injector.register("androidProjectService", AndroidProjectService);